【发布时间】:2012-06-08 22:02:23
【问题描述】:
首先我应该说我看到了这个链接:
How to refresh datagridview when closing child form?
我确实是这样的: (我在Form1中有datagridview) Form1:
public void FillDataGridView(DataTable dt1)
{
bindingSource1.DataSource = dt1;
bindingSource1.ResetBindings(false);
dataGridView1.DataSource = bindingSource1;
//here i checked number of rows of dt1 and it shows the correct value
}
Form2:
SqlConnection cnn = new SqlConnection(@"My connection string");
private Form1 Handled_frm1;
public Form2(Form1 frm1)
{
InitializeComponent();
Handled_frm1 = frm1;
}
private void textbox1_TextChanged(object sender, EventArgs e)
{
dt.Clear();
using (SqlCommand cmd =cnn.CreateCommand())
{
if (cnn.State == ConnectionState.Closed)
{
cnn.Open();
}
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = cnn;
cmd.CommandText = "spSearchCustomerByName";
SqlParameter inparam1 = cmd.Parameters.AddWithValue("@name", textbox1.Text);
inparam1.Direction = ParameterDirection.Input;
dap.SelectCommand = cmd;
dap.Fill(dt);
Handled_frm1.FillDataGridView(dt);
}
但是Datagridview的值没有变化!
已编辑:
我想测试我是否可以清除数据网格视图,所以我像这样更改了 FillDataGridView:
public void FillDataGridView(DataTable dt1)
{
dt.Clear();
dataGridView1.Columns.Clear();
dataGridView1.DataSource = null;
dataGridView1.Refresh();
}
但它并没有清除datagridview1!!!
【问题讨论】:
-
您的代码没有显示第二种形式的数据与您在第一种形式中使用的数据表之间的关系。例如,cnn 在哪里初始化?
-
可能是类似类型的 SO 问题 - stackoverflow.com/questions/2947818/… ?
-
@JohnB:cnn 在 Form2 中初始化,我编辑了我的问题
-
Handled_frm1 = fromSearchNewCustomer;应该是Handled_frm1 = frm1;,否则你只是丢弃了对父表单的引用。然后,当您调用Handled_frm1.FillDataGridView时,它会解析为正确的形式。 -
我在这里发错了,我更新了我的问题
标签: c# winforms datagridview