在我的程序中,我允许用户从列表框中选择学生记录,当他们单击编辑按钮时,将打开一个新表格。该表格显示他们选择的学生的ID和标记。我需要让用户编辑该标记并更新列表框。我无法让用户进行编辑,对此不胜感激。 (在将用户的数据保存在编辑表单中时,我很难弄清楚该怎么办)
不允许使用LINQ,因此不提供解决方案或建议,将不胜感激。
主要形式:
private void btnEditMark_Click(object sender, EventArgs e) {
string[] s_rec_arr;
if (lstMarks.SelectedIndex == -1) {
MessageBox.Show("please select a student");
} else {
ModuleData.s_rec = lstMarks.SelectedItem.ToString();
s_rec_arr = ModuleData.s_rec.Split(':');
ModuleData.s_id = s_rec_arr[0];
ModuleData.s_mark = s_rec_arr[1];
editMark myEditRecordForm = new editMark();
this.Hide();
myEditRecordForm.ShowDialog();
}
}
编辑表单:
public partial class editMark : Form {
public editMark() {
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
txtStudentID.Focus();
}
private void btnSubmit_Click(object sender, EventArgs e) {
}
private void btnClose_Click(object sender, EventArgs e) {
this.Hide();
Form1 myForm = new Form1();
myForm.ShowDialog();
}
private void editMark_Load(object sender, EventArgs e) {
txtStudentID.Text = ModuleData.s_id;
txtMark.Text = ModuleData.s_mark;
}
}
答案 0 :(得分:0)
您可以将任何类型的对象添加到列表框中,而不仅仅是字符串。创建一个学生班级,并将Student
对象添加到列表框中。或者,您可能更喜欢使用ModuleData
类。但是无论如何,您都不需要将s_rec
与冒号分隔的字符串一起使用。
public class Student
{
public string Id { get; set; }
public string Mark { get; set; }
// Required to make to have the list box display useful information about students.
public override string ToString()
{
return $"Id = {Id}, Mark = {Mark}";
}
}
现在将参数添加到编辑表单的构造函数中,以使学生能够通过
private Student _student;
public editMark(Student student)
{
InitializeComponent();
// Remember the student
_student = student;
StartPosition = FormStartPosition.CenterScreen;
txtStudentID.Text = student.Id;
txtMark.Text = student.Mark;
txtStudentID.Focus();
}
在editform中,如果您执行Form1 myForm = new Form1();
,则将创建Form1
的新实例,而不是使用现有的隐藏实例。
请记住,班级是引用类型,因此不必将学生传递回第一个表格,因为该表单也具有对同一学生的引用。仅更新其属性
private void btnClose_Click(object sender, EventArgs e)
{
_student.Id = txtStudentID.Text; // Only id the Id is editable.
_student.Mark = txtMark.Text;
Close();
}
主要形式
private void BtnEditMark_Click(object sender, EventArgs e)
{
if (lstMarks.SelectedIndex == -1) {
MessageBox.Show("please select a student");
} else {
var student = (Student)lstMarks.SelectedItem;
// Pass the student as to the edit form
var myEditRecordForm = new editMark(student);
Hide();
myEditRecordForm.ShowDialog(); // The code pauses here until the edit form is closed.
Show(); // Doing this here prevents you from having the edit form knowing about Form1.
// To display the changes.
lstMarks.Items[lstMarks.SelectedIndex] = student;
}
}