Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...