从另一个表单更新datagridview中的选定行 [英] update selected row in datagridview from another form

查看:146
本文介绍了从另一个表单更新datagridview中的选定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个Form1和Form2格式,我想从Form2
更新Form1中的datagridview,首先我在Form1中选择datagridview行,然后点击一个按钮打开Form2。
在Form2中我输入新数据然后保存。



我该怎么做?

解决方案

我的解决方案类似于@Michael Perrenoud的。您的目的是将值从form1传递给form2。如何通过?通常你需要通过form2的构造函数将form1中的对象传递给form2。那么,通过什么?其他人说通过form1本身或通过gridview控件,但我更喜欢传递你真正想要在form2中使用的数据,为什么?因为当你传递一个控件(form或gridview)时,需要分析并获取数据,然后在form2中加入gridview2,想想当你从form1传递控件时,也许有一天你会用gridview替换其他控件,如listview或treeview,甚至有一天你可能放弃form1,所以你需要修改和重构你的form2。但是如果仅传递数据,则可以重用form2。以下是我的示例代码:



首先,添加一个私有字段引用您传递的数据

  private object mydata = null; 

添加一个函数来填充gridview与传递的数据

  public void FillData(...)
{
if(mydata!= null)
{
// add数据进入gridview
}
}

然后,添加一个新的构造函数Form2:

  public Form2(object data)
{
_mydata = data;
}

当您要显示form2时,请从gridview1获取数据

  void ShowData()
{
对象mydata = null;
//从所选行获取数据并设置为mydata
Form2 f = new Form2(mydata);
f.ShowDialog();
}


I have 2 form Form1 and Form2, I want to update datagridview in Form1 from Form2 first i select the row of datagridview in Form1 then click a button to open Form2. in Form2 I input the new data then save it.

how I can do that?

解决方案

My solution is similar to @Michael Perrenoud's. Your purpose is to pass value from form1 to form2. How to pass? usually you need to pass the object in form1 to form2 by constructor of form2. then, what to pass? others say pass the form1 itself or pass the gridview control, but I prefer to pass the data you really want to use in form2, why? because when you pass a control(form or gridview), you need to analyse and get the data with it, then add to gridview2 in form2, think about that, when you pass control from form1, maybe one day you will replace the gridview by other controls such as listview or treeview, evenmore, that one day you may abandon form1, so you need to modify and Refactor your form2. but if you pass the data only, you can reuse the form2. here is my sample code:

first, add a private field refering to your passed data

private object mydata = null;

add a function to fill the gridview with the passed data

public void FillData( ... )
{
    if(mydata != null)
    {
    //add the data into gridview
     }
}

then, add a new constructor to Form2:

public Form2(object data)
{
    _mydata = data;
}

when you want to show form2, please get the data from gridview1

void ShowData()
{
     object mydata = null;
     //get the data from selected rows and set to mydata
     Form2 f = new Form2(mydata);
     f.ShowDialog();
}

这篇关于从另一个表单更新datagridview中的选定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆