【问题标题】:How can I pass data to DataGridView from another form?如何将数据从另一个表单传递给 DataGridView?
【发布时间】:2015-11-05 17:26:16
【问题描述】:

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

我有 2 个窗体:

  • form1 包含 DataGridView1button_frm1DataGridView 有 3 列并且已经有一些数据(6 行)并且 DataGridView1 修饰符 = Public。

  • form2 包含textBox1button_frm2

现在,当我单击 button_frm1 时出现 form2,然后当我单击 button_frm2 时,文本框中的值应插入到所选行的 column0 中的 DataGridView1 中。但相反,我收到了这个错误:

索引超出范围。必须为非负数且小于集合的大小。

请帮助我如何将 form2 中的 textBox 值插入到 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();


    }
}

【问题讨论】:

  • 如何填充 DataGridView?
  • @naouf 你试过我的方法了吗?我理解正确吗?
  • 嗨,StepUp。谢谢您的回复。我仍然没有尝试过,因为我是 c# 新手,而且你的代码对我来说是新的,所以我仍在努力理解它。但是,一旦我尝试它,我会告诉你。你能告诉我应该在 c# 的哪个区域搜索以理解你的代码吗?谢谢。

标签: c# .net datagridview


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多