从另一个表单更新 Datagridview [英] Update Datagridview From Another Form
问题描述
首先我应该说我看到了这个链接:
First I should say i saw this link :
我确实是这样的:(我在 Form1 中有 datagridview)Form1:
And i did like this: (i have datagridview in Form1) 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的值并没有改变!
But the value Of Datagridview does not change!
已
我想测试我是否可以清除数据网格视图,所以我像这样更改了 FillDataGridView:
I wanted to test that if i can clear datagrid view or not,so i changed FillDataGridView like this :
public void FillDataGridView(DataTable dt1)
{
dt.Clear();
dataGridView1.Columns.Clear();
dataGridView1.DataSource = null;
dataGridView1.Refresh();
}
但它没有清除datagridview1!!!
but it does not clear datagridview1!!!
推荐答案
我错误地使用了一个不正确的 Form1 实例!!
I Used mistakenly an incorrect instance of Form1!!
在form1中,有一个按钮,当点击它时,它显示form2.我在它的点击事件中写了这段代码:
in form1,there is a button that when click it,it shows form2.i wrote this code in click event of it:
Form1 frm1=new Form1();
Form2 frm2=new Form2(frm1);
这是不正确的,因为我创建了 Form1 的附加实例.
and this was incorrect,because i made additional instance of Form1.
我把代码改成这样:
Form2 frm2=new Form2(this);
这篇关于从另一个表单更新 Datagridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!