使用form2中的更改更新form1中的datagridview

时间:2011-08-19 16:04:52

标签: c# .net winforms data-binding datagridview

我已经完成了在一个表单中单击一个datagridview行单元格,表单1表示另一个表单,表单2将与form1上的选定数据网格视图数据一起打开..

我正在使用winforms ... c#

我对数据网格视图数据进行了一些操作,在操作阶段结束时,form2将被关闭

    NOTE :upto this i have  finished

我想更新form1中的datagridview,其中包含我在form2中所做的更改

因为我已经这样做了..

表单1:

     private void productGridview_Cellclick(object sender, DataGridViewCellEventArgs e)
     {

         if (e.ColumnIndex != productgridview.Columns["productimage"].Index) return;

            if (productgridview.SelectedCells.Count == 0) return;

            int selectedrowindex= productgridview.SelectedCells[0].RowIndex;

            DataGridViewRow selectedRow = productgridview.Rows[selectedrowindex];
              if (img is Image)
               {
                   using (ProductDescriptionForm pf = new ProductDescriptionForm())
                   {

                       pf.picture = img;
                       pf.productname = productname;
                       pf.description = desc;
                       pf.productprice = productprices;
                       pf.categoryname = categoryCombobox.Text;
                       pf.productid = productids;
                       pf.ShowDialog(this);
                   }
               }
      }

并且在form2中:我这样做了......

         public int productid
    {
        get { return _prodid; }
        set { _prodid = value; }

    }
    public Image picture
    {
        get { return pictureBox1.Image; } 
        set { pictureBox1.Image = value; }
    }
   like this  some constructors  i have used and then 

我使用下面的代码删除了datagridview中的一行......很好..

      private void btnProdDelete_Click(object sender, EventArgs e)
      {
        using(var context = new TsgEclipseEntities())
        {
              var pd = new product(){ product_Id = productid };
              context.products.Attach(pd);
              context.DeleteObject(pd);
              context.SaveChanges();
              this.Close();   // form2 close                   
       }

    }

现在我想更新form1中的datagridview我该怎么做.....

任何人都可以对此有所了解......

非常感谢....

3 个答案:

答案 0 :(得分:1)

1)编写一个数据绑定方法,该方法接受product_id参数以获取表单1中的数据 2)在form2.close之前,初始化表单1类,并通过传递刚更新的product_id并打开form1来调用方法。

答案 1 :(得分:0)

在Form1中,在Form1中创建一个BindingSource,使用它作为Form1中Grid的数据源。将相同的绑定源传递给Form2。将其用作Form2中网格的数据源。

这些变化将是无缝的。

答案 2 :(得分:0)

在关闭表单之前在Form2 btnProdDelete_Click事件中将DialogResult设置为OK - this.DialogResult = OK; 在您使用ProductDescriptionForm pf中 - 显示对话框后 - 如果结果是X,则查看结果是否正常取消, 在ShowDialog之后,您现在可以访问公共财产productid  并且您可以使用该productid在表单1中执行您想要的操作,您无需创建表单1的实例 - 它就像魔术一样。

A quick easy example of passing data from form2 to form 1