更新数据后,客户列表不刷新显示
来源:10-9 【实战】更新数据
weixin_慕码人1245530
2023-07-14
请问老师:
更新数据后,
ShowCustomers代码
private void ShowCustomers() {
//为避免数据库读取中可能会出现的错误,可以用try来处理
try
{
string sql = "select * from Customers";
//桥接器 将DataSet和数据库连接
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
//using可以将资源自动释放
using (sda)
{
//DataTable:一个内存内关系数据的表
DataTable customerTable = new DataTable();
//将桥接器中存放的数据放到表里面
sda.Fill(customerTable);
// 这里的数据将在List中展示
this.CustomerList.DisplayMemberPath = "Name";
//这里的数据是被选择的数据
this.CustomerList.SelectedValuePath = "Id";
//指定List的数据源
this.CustomerList.ItemsSource = customerTable.DefaultView;
}
}
//发生错误时,会将错误信息展示出来
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
更新客户代码
try
{
string sql = "update Customers set Name = @name,IdNnumber = @Id,Address = @Address where Id = @CustomersId";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("@name", this.Name.Text.Trim());
cmd.Parameters.AddWithValue("@Id", this.Number.Text.Trim());
cmd.Parameters.AddWithValue("@Address", this.Address.Text.Trim());
cmd.Parameters.AddWithValue("@CustomersId", this.CustomerList.SelectedValue);
con.Open();
cmd.ExecuteScalar();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
finally
{
con.Close();
this.ShowCustomers();
}

执行以上代码后,客户列表数据会消失,但如果在另一个按钮里,执行ShowCustomers(),客户列表数据又正常显示了。
对了半天代码,除了命名不一样,其他的都跟老师一样,不知道是为什么?还请老师指点。
写回答
1回答
-
阿莱克斯刘
2023-07-15
从你提供的代码中我看不出有什么问题,可否提供更清晰的代码?可以发到我邮箱,382231334@qq.com022023-07-16
相似问题