call variable from another form c#

后端 未结 3 1056
时光说笑
时光说笑 2020-12-12 04:24

I have a DataGridView in Form1 and I\'m using this code to display another form called Generator:

private void button1         


        
3条回答
  •  忘掉有多难
    2020-12-12 05:02

    Form 1:

    private void button1_Click(object sender, EventArgs e)
    {
        Form gen = new Generator(this.mydatagridview);
        gen.Show();
    }
    

    Generator Form:

    DataGridView _dataGridView;
    public Generator(DataGridView dataGridView)
    {
        InitializeComponent();
        this._dataGridView = dataGridView;
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
        this._dataGridView...! // this will work
    }
    

    Things that you must do, and know (just tips, you are not forced to do these but I believe you will be a better programmer if you do! ;)

    Always call InitializeComponent() in all form constructors. In your sample you didn't call it in one of the constructors.

    C# knows only information of the type you have passed. If you pass a Form, then you only get Form properties (i.e. the properties of type Form), not the properties of your own form.

    Try to encapsulate things. Do not pass a whole form to another form. Instead, pass things that you would like to use on the other form.

提交回复
热议问题