2

我是 C# 的初学者,我有两种形式mainFormsubForm. mainFormDataGridView1subFormrichTextBox1。_

我想通过 FormClosingEvent 添加DataGridView1subForm

我将DataGridView1修饰符设为public。它以智能方式显示,subForm但也许我做错了什么。

我在我的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);               
        }

提前致谢

4

1 回答 1

3

因此,假设您的 mainForm 打开了您的 subForm:

subForm sub = new SubForm();
sub.Show(); // or however you have done it

在您的示例中,您需要 subForm 能够更改主窗体上的某些内容,因此,在 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;
}

在 mainform 之后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);               
    }

我希望这会有所帮助!

于 2012-09-26T05:53:04.800 回答