0

我有一个包含带有按钮单元格的dataGridView的表单。我也有第二种形式,有一个文本框。如何将Form2中的文本传输到Form1上的dataGridView?如何将文本从From2传输到Form1中的dataGridView单元格C#

例如:

我在DataGridView的纽扣电池点击启动第二个形式,第二形式我选择一个单选按钮,从应对文本,然后点击一个按钮,将文本传输到单击的单元格在Form1中的dataGridView中。

这是我到目前为止的代码:

Form1中(Top_Shine_Form):

namespace Top_Shine 
{ 
public partial class Top_Shine_Form : Form 
{ 
    public Top_Shine_Form() 
    { 
     InitializeComponent(); 
    } 

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) 
    { 
     if(e.ColumnIndex >= 2) 
     { 
      Form2 f2 = new Form2(); 
      f2.ShowDialog(); 
     } 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 

     if (radioButton1.Checked) 
     { 
      DataTable dgv1 = new DataTable(); 
      dgv1.Columns.Add("Time"); 
      dgv1.Columns.Add("CarColorNumber"); 
      dgv1.Columns.Add("Interior"); 
      dgv1.Columns.Add("Exterior"); 

      DataRow row = dgv1.NewRow(); 
      row["Time"] = Timetxt.Text; 
      row["CarColorNumber"] = CNametxt.Text + "/" + CColortxt.Text + "/" + CNumbertxt.Text; 

      row["Interior"] = "*"; 
      row["Exterior"] = "*"; 

      dgv1.Rows.Add(row); 

      foreach (DataRow dr in dgv1.Rows) 
      { 
       int num = dataGridView1.Rows.Add(); 
       dataGridView1.Rows[num].Cells[0].Value = dr["Time"].ToString(); 
       dataGridView1.Rows[num].Cells[1].Value = dr["CarColorNumber"].ToString(); 

       if (interiorCB.Checked) 
       { 
        dataGridView1.Rows[num].Cells[2].Value = dr["Interior"].ToString(); 
       } 
       if (ExteriorCB.Checked) 
       { 
        dataGridView1.Rows[num].Cells[3].Value = dr["Exterior"].ToString(); 
       } 

      } 
      radioButton1.Checked = false; 
     } 

     CNametxt.Clear(); 
     CColortxt.Clear(); 
     CNumbertxt.Clear(); 
     Timetxt.Clear(); 
     interiorCB.Checked = false; 
     ExteriorCB.Checked = false; 
    } 
    } 
} 

这是我的Form2代码:

namespace Top_Shine 
{ 
public partial class Form2 : Form 
{ 
    public Form2() 
    { 
     InitializeComponent(); 
    } 

    private Top_Shine_Form frm = new Top_Shine_Form(); 
    private void button1_Click(object sender, EventArgs e) 
    { 
     int num = frm.dataGridView1.Rows.Add(); 
     if (radioButton1.Checked) 
     { 
      frm.dataGridView1.CurrentCell.Value = radioButton1.Text; 
     } 
    } 
    } 
} 

现在一切都正常运行,直到我单击Form2上的按钮以传输文本。并显示以下错误:

An unhandled exception of type 'System.NullReferenceException' occurred in Top Shine.exe 

Additional information: Object reference not set to an instance of an object. 

我究竟在做什么错?

感谢您的帮助。

回答

0

的解决方案很简单其实,你改变了:

private Top_Shine_Form frm = new Top_Shine_Form(); 

要:

public static string passingText; 

在窗体2按钮:

passingText = radioButton1.Text; 

在Form1上dataGridView1_CellContentClick:

dataGridView1.CurrentCell.Value = Form2.passingText; 
相关问题