Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
582 views
in Technique[技术] by (71.8m points)

winforms - call variable from another form C#

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

private void button1_Click(object sender, EventArgs e)
{
   Form gen = new Generator();
   // Form gen = new Generator(Form this); //* I tried this but is not working *//
   gen.Show();
}

In the Generator form I need to read or modify something in the datagridview which is in the Form1.

public partial class Generator : Form
{
   public Form myForm;

   public Generator()
   {
      InitializeComponent();
   }

   public Generator(Form frm)
   {
      myForm = frm;
   }

   private void button1_Click(object sender, EventArgs e)
   {
      myForm.mydatagridview.! // this is not working
   }
}

How can I resolve this problem, so I can manipulate the DataGridView from the Generator form?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...