I have a ListView and the ListView data is taken from database.
Beside the ListView got a button to add the record.
if the button is pressed it will show a dialog
Code :
private void bAddStudent_Click(object sender, EventArgs e) {
fAddStudent addStudent = new fAddStudent();
addStudent.ShowDialog();
}
After add the record, the dialog will close() and show the ListView.
But the ListView is not update the data.
Is there any way to make it auto update?
Edit :
Here is how I add records :
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();
}
}
Code For showing 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);
}
Note
‘Add data’ form is different with showing the ListView form, so I cannot access the ListView in the ‘add data’ form
You need to call databind() method every time you want your data to be refreshed.
From what I understood you a)show the data, b) add new record to database but new record is not shown. If this is the case just call DataBind() method and it should work.