我有一个ListView
,ListView
数据是从数据库中获取的。旁边ListView
有一个按钮来添加记录。
如果按下按钮,它将显示一个对话框
代码 :
private void bAddStudent_Click(object sender, EventArgs e) {
fAddStudent addStudent = new fAddStudent();
addStudent.ShowDialog();
}
添加记录后,对话框将close()
显示 ListView。但ListView
不是更新数据。
有没有办法让它自动更新?
编辑: 这是我添加记录的方式:
private void btnAdd_Click(object sender, EventArgs e) {
string studentID = tbStudentId.Text;
string studentName = tbStudentName.Text;
string gender = tbGender.Text;
string connectionString = "Data Source=xxx\\SQLEXPRESS;Initial Catalog=TestApplication;Integrated Security=SSPI; User ID=xxx;Password=xxx";
using (SqlConnection connection = new SqlConnection(connectionString)) {
SqlCommand cmd = new SqlCommand("INSERT INTO student (student_id, student_name, student_gender) VALUES (@studentId, @studentname, @studentGender) ");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("@studentId", studentID);
cmd.Parameters.AddWithValue("@studentName", studentName);
cmd.Parameters.AddWithValue("@studentGender", gender);
connection.Open();
cmd.ExecuteNonQuery();
}
}
显示代码ListView
:
List<string> myListHeader = new List<string>(new string[] { "ID", "Name", "Gender" });
myListHeader.ForEach(name => lvStudent.Columns.Add(name));
SqlConnection UGIcon = new SqlConnection();
UGIcon.ConnectionString = "Data Source=xxx\\SQLEXPRESS;Initial Catalog=TestApplication;Integrated Security=SSPI; User ID=xxx\\user;Password=xxx";
UGIcon.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM student", UGIcon);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
ListViewItem item = new ListViewItem(dr[0].ToString());
item.SubItems.Add(dr[1].ToString());
item.SubItems.Add(dr[2].ToString());
lvStudent.Items.Add(item);
}
笔记
“添加数据”表单与显示ListView
表单不同,因此我无法访问ListView
“添加数据”表单