从另一个表单更新Datagridview

时间:2012-06-04 20:31:45

标签: c# winforms datagridview

首先我应该说我看到了这个链接:

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
            }

窗体2:

           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的价值不会改变!

编辑:

我想测试一下,如果我可以清除datagrid视图,所以我改变了FillDataGridView:

                public void FillDataGridView(DataTable dt1)
            {
                    dt.Clear();
                    dataGridView1.Columns.Clear();
                    dataGridView1.DataSource = null;
                    dataGridView1.Refresh();
            }

但它没有清除datagridview1 !!!

2 个答案:

答案 0 :(得分:2)

我错误地使用了Form1的错误实例!!

在form1中,有一个按钮,点击它时,它显示form2.i在点击事件中写了这段代码:

Form1 frm1=new Form1();
Form2 frm2=new Form2(frm1);

这是不正确的,因为我创建了Form1的其他实例。

我改变代码如下:

Form2 frm2=new Form2(this);

答案 1 :(得分:1)

尝试使用BindingSource,如以下链接中所述:

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.datasource

我认为直接设置DataSource不会导致DataGridView重新绑定,而BindingSource负责处理。

相关问题