首页 文章

如何从另一个表单将数据传递给DataGridView?

提问于
浏览
1

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

我有2个窗口形式:

  • form1 包含 DataGridView1button_frm1 . DataGridView 有3列,已经有一些数据(6行)和 DataGridView1 modifiers = Public .

  • form2 包含 textBox1button_frm2 .

现在,当我单击 button_frm1 form2时出现,然后单击 button_frm2 时,应将textBox中的值插入所选行的column0中的 DataGridView1 . 但相反,我得到了这个错误:

指数超出范围 . 必须是非负数且小于集合的大小 .

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

这是我试过的代码:

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


    }
}

1 回答

  • 0

    首先创建一个包含有关事件数据的类:

    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;
    

    并在事件的事件处理程序“单击”Form2的按钮:

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

相关问题