call variable from another form c#

后端 未结 3 1060
时光说笑
时光说笑 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 04:55

    A few things are going on here.

    1. You have to use the constructor of Generator that take in a form as a parameter.
    2. You have to expose the datagridview as a public or internal property on the form that you will pass into Generator.
    3. The normal Form class will not know about this property, so you should cast the variable appropriately.
    4. You should call the default constructor of Generator when the other constructor is used to make sure everything is initialized correctly. See code sample below.

    Something like this should work:

    public class Generator
    {
        private MyForm myForm;
    
        public Generator()
        {
            InitializeComponent();
        }
    
        public Generator(MyForm frm) : this() // DON'T FORGET THIS()
        {
            myForm = frm;
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            myForm.MyDataGridView... // Yay, it works!
        }
    }
    
    public class MyForm : Form
    {
        public MyForm()
        {
            InitializeComponent(); // a datagridview is created here, say "datagridview1"
        }
    
        public DataGridView MyDataGridView
        {
            get { return datagridview1; }
        }
    }
    

    And then in your button click event (which I assume is defined somewhere in MyForm):

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

提交回复
热议问题