如何从其他窗体访问DataGridView



在表单1中,我创建了一个用数据库填充行的数据网格视图。在表单2中,我想向用户显示表单1中数据网格视图的特定行。特定行由用户选择!!!我在public修饰符中设置了datagridview,这就是我的表单2代码:

form1 parentsell = new form1();
string selecteduser = parentsell.propertydatagrid.Rows[selectedrowindex].Cells[72].Value.ToString();
MessageBox.Show(selecteduser);

当程序构建时并没有错误,但运行后会给我一个错误。

因此,您可能使用查找表单,您需要通过引用传递值,最简单的方法是将类User装箱,如下所示:

public Class User
{
public string name {get; set;}
}

然后你可以在主窗体中创建该对象的实例,比如这个

User user = new User();
form1 parentsell = new form1(user);
parentsell.ShowDialog(); // This will open another form and wait you to finish work
MessageBox.Show(user.name);

在表单1中,您需要创建另一个构造函数和User实例

User user;
public form1(User user)
{
InitializeComponent();
this.user = user;
}

现在你需要一些按钮,上面会写着"好吧,我找到了这个用户,现在带他关闭这个表单",就像这样:

private void button1_Click(object Sender, EventArgs e)
{
user.name = ...; //find your user, DGV.selectedRows[0].Cells[somehing].Value.ToString(); I think it's like this...
this.Close();
}

你应该在主表单中获得你选择的用户

一种非常简单的方法:

将此行添加到您想要访问数据网格视图的另一个表单(例如Form2(中:

public static DataGridView view { get; set; }

然后转到包含要访问的DataGridView(例如dataGridView1(的表单(例如Form1(。将此行添加到表单中:

foreach(DataGridViewRow row in dataGridView1.Rows)
{
Form2.view.Rows.Add(row.Cells["Column1"].Value);
Form2.view.Rows.Add(row.Cells["Column2"].Value);
} 

添加一个文本框(例如textBox1(,让用户添加所需行的索引,并以这种方式在新的datagridview(例如dataGridView2(中获取它:

dataGridView2.Rows.Clear();
dataGridView2.Rows.Add(view.Rows[Convert.ToInt32(textBox1.Text)].Cells["Column1"].Value, view.Rows[Convert.ToInt32(textBox1.Text)].Cells["Column2"].Value)

请记住,datagridview行索引从"0"开始。

还记得在运行代码之前向dataGridView2添加两列。


您也可以直接将数据库中的数据调用到所需的表单,而不是从另一个datagridview中获取数据。

最新更新