C# 如何将数据从另一个表单传递到DataGridView?
我只是想将数据从另一个表单传递到DataGridView 我有两个windows窗体:C# 如何将数据从另一个表单传递到DataGridView?,c#,.net,datagridview,C#,.net,Datagridview,我只是想将数据从另一个表单传递到DataGridView 我有两个windows窗体: form1包含DataGridView1和按钮\u frm1。DataGridView有3列,并且已经有一些数据(6行)和DataGridView 1modifiers=Public form2包含textBox1和按钮 现在,当我单击按钮\u frm1form2出现时,下一步当我单击按钮\u frm2时,文本框中的值应插入所选行第0列中的DataGridView1。但是,我得到了这个错误: 索引超出范围
包含form1
和DataGridView1
。按钮\u frm1
有3列,并且已经有一些数据(6行)和DataGridView
modifiers=PublicDataGridView 1
包含form2
和textBox1
按钮
按钮\u frm1
form2出现时,下一步当我单击按钮\u frm2
时,文本框中的值应插入所选行第0列中的DataGridView1
。但是,我得到了这个错误:
索引超出范围。必须为非负数且小于集合的大小
请帮助我如何将form2中的文本框值插入form1中的DataGridView1。要遵循哪些步骤?
事先非常感谢
以下是我尝试的代码:
表格1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button_frm1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.Show();
}
}
表格2:
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();
}
}
首先,创建一个包含事件数据的类:
public class ValueEventArgs : EventArgs
{
private string _smth;
public ValueEventArgs(string smth)
{
this._smth = smth;
}
public string Someth_property
{
get { return _smth; }
}
}
然后在Form2中声明事件和事件处理程序:
public delegate void FieldUpdateHandler(object sender, ValueEventArgs e);
public event FieldUpdateHandler FieldUpdate;
private void button_frm2(object sender, EventArgs e)
{
//Transfer data from Form2 to Form1
string dataToTransfer=textBox1.Text;
ValueEventArgs args = new ValueEventArgs(str);
FieldUpdate(this, args);
this.Close();
}
在窗体2按钮的事件处理程序“单击”处:
public delegate void FieldUpdateHandler(object sender, ValueEventArgs e);
public event FieldUpdateHandler FieldUpdate;
private void button_frm2(object sender, EventArgs e)
{
//Transfer data from Form2 to Form1
string dataToTransfer=textBox1.Text;
ValueEventArgs args = new ValueEventArgs(str);
FieldUpdate(this, args);
this.Close();
}
然后写下从form1调用form2的位置:
private void button_frm1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.FieldUpdate += new AddStuff.FieldUpdateHandler(af_FieldUpdate);
frm2.Show();
}
void af_FieldUpdate(object sender, ValueEventArgs e)
{
DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
row.Cells[0].Value = e.Someth_property;
row.Cells[1].Value = "YourValue";
/*or
this.dataGridView1.Rows.Add("1", "2", "three");
this.dataGridView1.Rows.Insert(0, "one", "two", "three");
*/
dataGridView1.Rows.Add(row);
}
如何填充您的DataGridView?@naouf您尝试过我的方法吗?我没听错吧?嗨,快点。谢谢你的回复。我仍然没有尝试,因为我是c#新手,而你的代码对我来说是新的东西,所以我仍然在尝试理解它。然而,一旦我尝试它,我会让你知道。你能告诉我应该在c#的哪个区域搜索以理解你的代码吗?非常感谢。