【发布时间】:2016-06-22 09:37:40
【问题描述】:
我想刷新数据网格视图,但它不起作用 我有这样的 Refresh 方法:
public void Select()
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
string cs = "server=(local);database=DB_Taxi;trusted_connection=yes;";
con.ConnectionString = cs;
con.Open();
cmd.Connection = con;
da.SelectCommand = cmd;
cmd.CommandText = "SELECT * FROM Tbl_Driver";
da.Fill(dt);
con.Close();
grid.DataSource = dt;
}
它在主窗体上。 我想以另一种名为 Add_Driver 的形式调用此函数。 为此,我在提交按钮中这样告诉它,因为我得到相同的文本框值,并且在提交它们之后,我想在数据库的数据网格视图中显示它们。 我这样称呼它:
private void btnOK_Click(object sender, EventArgs e)
{
if (txtID.Text != "" || txtName.Text != "" || txtLastName.Text != "" || txtMobile.Text != "" ||
txtPhone.Text != "" || txtCar.Text != "" || txtGender.Text != "" || txtAddress.Text != "")
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
string cs = "server=(local);database=DB_Taxi;trusted_connection=yes;";
con.ConnectionString = cs;
con.Open();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO Tbl_Driver(DriverID,DName,DLastName,DMobile,DAddress,DCar,DGender,DPhone) VALUES(@ID,@Name,@LastName,@Mobile,@Address,@Car,@Gender,@Phone)";
cmd.Parameters.AddWithValue("@ID", txtID.Text);
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("@Mobile", txtMobile.Text);
cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
cmd.Parameters.AddWithValue("@Car", txtCar.Text);
cmd.Parameters.AddWithValue("@Gender", txtGender.Text);
cmd.Parameters.AddWithValue("@Phone", txtPhone.Text);
cmd.ExecuteNonQuery();
con.Close();
Empty();
////////////////////
Main m = new Main();
m.Select();
////////////////////
MessageBox.Show("Added");
}
else
{
MessageBox.Show("Plese complete the form");
}
}
但数据网格视图上的数据不会改变。 请帮忙! 但是当我在主窗体上调用此方法时,它可以工作 但我这样写 main 方法:
Select()
【问题讨论】:
-
您是否调试过代码并查看发生了什么?
-
使用 MVVM 模式效果更好。
-
是的,我调试了它。但没有什么异常。
-
尝试先将Datasource设置为
null,然后再设置实际来源。 -
1) 带有数据的主窗体打开 Form2。 2) Form2 触发
btnOK_Click填充主窗体的一个新实例。 (您现在拥有 Main - 原始数据、Form2、Main - 新数据)3) Form2 关闭(丢失 Main 的新实例) - 只剩下原始 Main 表单及其原始数据。 TLDR; 不要在后续表单中填充Main的新实例。Main m = new Main()应该引用现有的表单。
标签: c# database datagridview refresh