2015-11-05 155 views
1

我只想将数据从另一个表单传递给DataGridView?如何从其他表单传递数据到DataGridView?

我有2点窗口的形式:

  • form1包含DataGridView1button_frm1DataGridView有3列,已经有一些数据(6行),DataGridView1 modifiers = Public。

  • form2包含textBox1button_frm2。现在

,当我点击button_frm1窗口2出现,接下来当我点击button_frm2在文本框中的值应该选择行插入DataGridView1在column0。但是,相反,我得到这个错误:

Index was out of range. Must be non-negative and less than the size of the collection.

请帮助我如何从Form2的文本框中的值插入DataGridView1在Form1。遵循什么步骤? 非常感谢您提前。

这里是我尝试的代码:

Form1中:

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(); 


    } 
} 
+0

如何填充您的DataGridView? – StepUp

+0

@naouf你试过我的方法吗?我理解正确吗? – StepUp

+0

嗨StepUp。谢谢您的回复。我仍然没有尝试它,因为我是c#的新手,你的代码对我来说是新的东西,所以我仍然试图理解它。但是,一旦我尝试它,我会让你知道。你能告诉我在c#的哪个区域应该搜索来理解你的代码吗?谢谢。 – naouf

回答

0

起初创建包含关于事件的数据的类:

public class ValueEventArgs : EventArgs 
{ 
    private string _smth; 
    public ValueEventArgs(string smth) 
    { 
     this._smth = smth; 
    } 
    public string Someth_property 
    { 
     get { return _smth; } 
    }  
} 

然后声明一个事件和事件处理程序的窗体2:

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窗体2:

public delegate void FieldUpdateHandler(object sender, ValueEventArgs e); 
public event FieldUpdateHandler FieldUpdate; 

,并在事件的事件处理程序的窗体2的按钮的“点击”:

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); 
} 
相关问题