In this section, I am going explain two methods for passing variables from one form to another in a windows application
1) Constructor Method 2) Property Method
I explain both using an example: We have form “FormA”, It’s having one text box and button control. And also have second form “FormB” having one label control. What is we want to achieve is that while clicking on button from FormA. We need to show the value of FormA’s textbox in label of FormB. Ie we need to pass one value from FormA to FormB
Constructor Method
In Constructor Method Basically create an overloaded Form Construer in receiving form (Here it is FormB), which will take parameters as receiving items. Code for FormA
public partial class FormA : Form {
private void button1_Click(object sender, EventArgs e) { FormB b = new FormB(txtStr.Text); b.Show(); }
}
Code for FormB
public partial class FormB : Form { public FormB() { InitializeComponent(); }
public FormB(string StringFromA) { InitializeComponent(); lbl.Text = StringFromA; }
}
Property Method
In this we will create public write only properties for FormB, which will accept variable to be passed FormA
Code for FormA
public partial class FormA : Form {
private void button2_Click(object sender, EventArgs e) { FormB b = new FormB(); b.StringFromA = txtStr.Text; b.Show(); } }
Code for FormA
public partial class FormB : Form { public FormB() { InitializeComponent(); }
public string StringFromA { set { lbl.Text = value; } }
}
Note: Complete code for this application attached
AttachmentsPassingVariables.zip (29908-3223-PassingVariables.zip)
|
No responses found. Be the first to respond and make money from revenue sharing program.
|