以相同的形式显示信息c#

时间:2017-08-22 05:53:32

标签: c# forms datagridview communication

我使用以下代码将数据从3个文本框(表单2)传递到数据网格视图(表单1)。数据成功传递,但我面临的唯一问题是数据传递给f1类型的新形式!

private void button1_Click(object sender, EventArgs e)
        {

            Form1 f1 = new Form1();

            DataTable dt1 = new DataTable();
             f1.dataGridView2.DataSource = dt1;
             dt1.Columns.Add("MessageID", typeof(string));
             dt1.Columns.Add("Name", typeof(string));
              dt1.Columns.Add("Number", typeof(string));


            DataRow dr = dt1.NewRow();
            dr["MessageID"] = IDtext.Text; ;
            dr["Name"] = nameText.Text;
            dr["Number"] = numberText.Text;
            dt1.Rows.Add(dr);


            f1.Show();



        }

因此,每次我传递信息时,都会创建一个新窗口,并且我发送的先前数据不会出现在数据网格视图中!如何更正此信息?

1 个答案:

答案 0 :(得分:0)

您重构的代码:

class Form2
{
    delegate void PassDataDelegate(DataTable dt1);
    public event PassDataDelegate PassData;

    private void button1_Click(object sender, EventArgs e)
    {
        DataTable dt1 = new DataTable();
        dt1.Columns.Add("MessageID", typeof(string));
        dt1.Columns.Add("Name", typeof(string));
        dt1.Columns.Add("Number", typeof(string));

        DataRow dr = dt1.NewRow();
        dr["MessageID"] = IDtext.Text; ;
        dr["Name"] = nameText.Text;
        dr["Number"] = numberText.Text;
        dt1.Rows.Add(dr);

        // This is where you call your event
        PassData(dt1);
     }
}

class Form1
{
    // Your existing Form1 class definition

    private static void YourMethodWhereYouLaunchForm2()
    {
        Form2 f2 = new Form2();

        // Add this handler and you will get it invoked whenever you ask from Form2
        f2.PassData += Handle_DataPassed;
    }

    private void Handle_DataPassed(DataTable dt1)
    {
        // This is where you post the data now to the grid.
        dataGridView2.DataSource = dt1;
    }
}