我是c#的初学者,我有两种形式mainForm
和subForm
。 mainForm
有DataGridView1
而subForm
有richTextBox1
。
我想从DataGridView1
到 FormClosingEvent
subForm
添加行和列
我将DataGridView1
修饰符设为 public 。它在subForm
的intellisense中显示,但也许我做错了。
我在subForm
FormClosingEvent 中尝试了以下代码,但我看不到对DataGridView1
的任何更新。
if (richTextBox1.Text != "")
{
mainForm newMainForm = new mainForm();
newMainForm.dataGridView1.ColumnCount = 3;
newMainForm.dataGridView1.Columns[0].Name = "Product ID";
newMainForm.dataGridView1.Columns[1].Name = "Product Name";
newMainForm.dataGridView1.Columns[2].Name = "Product Price";
string[] row = new string[] { "1", "Product 1", "1000" };
newMainForm.dataGridView1.Rows.Add(row);
row = new string[] { "2", "Product 2", "2000" };
newMainForm.dataGridView1.Rows.Add(row);
row = new string[] { "3", "Product 3", "3000" };
newMainForm.dataGridView1.Rows.Add(row);
row = new string[] { "4", "Product 4", "4000" };
newMainForm.dataGridView1.Rows.Add(row);
}
提前致谢
答案 0 :(得分:3)
假设你的mainForm打开你的subForm:
subForm sub = new SubForm();
sub.Show(); // or however you have done it
在您的示例中,您需要subForm才能更改mainform上的内容,因此,在subForm上创建一个Public / Internal方法,类似于:
private mainForm _parent;
internal void RegisterParent(mainForm form)
{
// error handling of course, make sure form is not null, or you don't already have a parent
this._parent = form;
}
在主要表单中,在subForm.Show()
之后添加如下内容:
sub.RegisterParent(this);
现在你的subForm可以操作正确的mainform 实例:
if (richTextBox1.Text != "")
{
_parent.dataGridView1.ColumnCount = 3;
_parent.dataGridView1.Columns[0].Name = "Product ID";
_parent.dataGridView1.Columns[1].Name = "Product Name";
_parent.dataGridView1.Columns[2].Name = "Product Price";
string[] row = new string[] { "1", "Product 1", "1000" };
_parent.dataGridView1.Rows.Add(row);
row = new string[] { "2", "Product 2", "2000" };
_parent.dataGridView1.Rows.Add(row);
row = new string[] { "3", "Product 3", "3000" };
_parent.dataGridView1.Rows.Add(row);
row = new string[] { "4", "Product 4", "4000" };
_parent.dataGridView1.Rows.Add(row);
}
我希望有所帮助!