2 次元配列と、テキスト ボックスからリスト ボックスに値を追加するための追加ボタンと、リスト ボックスと配列から選択した値を削除するための削除ボタンがあります。
2 次元配列であるため、このコード行は機能しません。
名前[lstindex] = null;
string[,] names = new string[10,3];
const int STUDENT_NAME = 0;
const int STUDENT_ID = 1;
const int MAJOR = 2;
private void btnExit_Click(object sender, EventArgs e)
{
Close();
}
private void AssignArray(int Row)
{
names[Row,STUDENT_NAME] = txtStudentName.Text;
names[Row, STUDENT_ID] = txtStdBox.Text;
names[Row, MAJOR] = txtMJbox.Text;
}
private string BuildStudent(int Row)
{
string answser = "";
int UpperLimit = names.GetUpperBound(1);
for (int column = 0; column <= UpperLimit; column++)
{
answser += names[Row, column] + "";
}
return answser;
}
private void btnAdd_Click(object sender, EventArgs e)
{
//find location to use array
int position = lstStudents.Items.Count;
AssignArray(position);
lstStudents.Items.Add(BuildStudent(position));
names[position,MAJOR] = txtMJbox.Text;
//find last valid subscript
int maxIndex = names.GetUpperBound(0);
//if using last valid subscript disable add button
if (position == maxIndex)
{
btnAdd.Enabled = false;
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
int index = lstStudents.SelectedIndex;
if (index != -1)
{
//update array
AssignArray(index);
//names[index, STUDENT_NAME] = txtStudentName.Text;
//remove old entry
lstStudents.Items.RemoveAt(index);
//put a new entry in that spot
lstStudents.Items.Insert(index,names[index, STUDENT_NAME]);
//highlight entry for user
lstStudents.SelectedIndex = index;
}
else
{
MessageBox.Show("seleect student, then click update","error");
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
int lstindex = lstStudents.SelectedIndex;
//Delete the data for a student in the array
//and listbox, and keep the array and listbox synchronized.
names[lstindex] = null;
lstStudents.Items.RemoveAt(lstindex);
}