如何从另一个表单将数据传递给DataGridView? [英] How can I pass data to DataGridView from another form?

查看:100
本文介绍了如何从另一个表单将数据传递给DataGridView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想从另一个表单向DataGridView传递数据?

我有2个窗口形式:

- from1包含DataGridView1和button_frm1.DataGridView有3列,已经有一些数据(6行)和DataGridView1修饰符=公共。



- form2包含textBox1和button_frm2。



现在,当我单击button_frm1 form2时出现,然后当我单击button_frm2时,textBox中的值应插入到所选行的column0中的DataGridView1中。但相反,我得到了这个错误:索引超出了范围。必须是非负数且小于集合的大小。



请帮帮我将formBox中的textBox值插入到form1中的DataGridView1中。要采取什么措施?非常感谢你提前。



这是我试过的代码:



Form1:



公共部分类Form1:表格

{

public Form1()

{

InitializeComponent();

}



private void button_frm1_Click(object sender,EventArgs e)

{

Form2 frm2 = new Form2();

frm2.Show();

}

}



表格2:



公共部分课程表格2:表格



{

public Form2()

{

InitializeComponent();

}



private void button_frm2(对象发件人,EventArgs e)

{

Form1 frm1 = new Form1();

textBox1.Text = frm1.dataGridView1.SelectedRows [0] .Cells [0] .Value.ToString();





}

}

I just want to pass data to DataGridView from another form?
I have 2 windows forms:
- from1 contains DataGridView1 and button_frm1.The DataGridView have 3 columns and already have some data (6 rows) and DataGridView1 modifiers = Public.

- form2 contains textBox1 and button_frm2.

Now, when I click button_frm1 form2 appears and next when I click button_frm2 the value in the textBox should be inserted into DataGridView1 in column0 in the selected row. but instead, I got this error: "Index was out of range. Must be non-negative and less than the size of the collection".

Please help me how to insert the textBox value from form2 into DataGridView1 in form1. What steps to follow? Thank you very much in advance.

Here is the code I tried:

Form1:

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button_frm1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.Show();
}
}

Form2:

public partial class Form2 : Form

{
public Form2()
{
InitializeComponent();
}

private void button_frm2(object sender, EventArgs e)
{
Form1 frm1 = new Form1();
textBox1.Text= frm1.dataGridView1.SelectedRows[0].Cells[0].Value.ToString();


}
}

推荐答案

那不行。

你在另一个中创建每个表单的新实例,这意味着你永远不会回到原来的形式。



看看这里:在两种形式之间转移信息,第2部分:儿童到父母 [ ^ ] - 它应该解释这个过程。
That won't work.
You are creating a new instance of each form in the other, which means that you never get back to the original form.

Have a look here: Transferring information between two forms, Part 2: Child to Parent[^] - it should explain the process.


这篇关于如何从另一个表单将数据传递给DataGridView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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