从另一个表单更新Datagridview [英] Update Datagridview From Another Form
问题描述
首先我应该说我看到这个链接:
First I should say i saw this link :
我这样做:
我在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的值不会更改!
But the value Of Datagridview does not change!
已编辑:
我想测试一下,如果我可以清除datagrid视图,那么我改变了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中错误地使用了一个不正确的Form1实例!
I Used mistakenly an incorrect instance of Form1!!
,有一个按钮当它点击它,它显示form2.i在它的点击事件中写这个代码:
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屋!