This is my class:
public class CowTypeDefaults
{
public static void LactatingCow()
{
Form1 frm = new Form1();
{
frm.CowAgetxtBox.Enabled = true;
frm.CowWeighttxtBox.Enabled = true;
frm.DaysPregtxtBox.Enabled = true;
frm.BCStxtBox.Enabled = true;
frm.DaysInMilktxtBox.Enabled = true;
frm.LactationNumbertxtBox.Enabled = true;
frm.FirstCalftxtBox.Enabled = true;
frm.CalfInttxtBox.Enabled = true;
frm.ADGpanel.Visible = false;
frm.CalfVarGroupBox.Enabled = false;
}
}
}
And I want to recall lactatingCow() in an event of my form and this is how i recall it:
private void CowTypeSelect_SelectedIndexChanged(object sender, EventArgs e)
{
if (CowTypeSelect.SelectedIndex == 0)
{
CowTypeDefaults.LactatingCow();
}
}
It shows no error and program runs but the code doesn't work and my text boxes are still disabled.
I don't know how fix it, thanks a lot for answering.
Because you are re-initiating Form1 frm = new Form1();
in the static method, so that in each call frm
will be different. Since this file is a separate class better option is to pass the object. So the method signature will be like:
public static void LactatingCow(Form1 frm)
{
frm.CowAgetxtBox.Enabled = true;
frm.CowWeighttxtBox.Enabled = true;
frm.DaysPregtxtBox.Enabled = true;
frm.BCStxtBox.Enabled = true;
frm.DaysInMilktxtBox.Enabled = true;
frm.LactationNumbertxtBox.Enabled = true;
frm.FirstCalftxtBox.Enabled = true;
frm.CalfInttxtBox.Enabled = true;
frm.ADGpanel.Visible = false;
frm.CalfVarGroupBox.Enabled = false;
}
And the button click will be :
private void CowTypeSelect_SelectedIndexChanged(object sender, EventArgs e)
{
if (CowTypeSelect.SelectedIndex == 0)
{
CowTypeDefaults.LactatingCow(this);
}
}
Well you're creating a new instance of Form1
everytime. Pass your form's instance as reference to you method:
public static void LactatingCow(Form1 form)
{
form.CowAgetxtBox.Enabled = true;
form.CowWeighttxtBox.Enabled = true;
form.DaysPregtxtBox.Enabled = true;
form.BCStxtBox.Enabled = true;
form.DaysInMilktxtBox.Enabled = true;
form.LactationNumbertxtBox.Enabled = true;
form.FirstCalftxtBox.Enabled = true;
form.CalfInttxtBox.Enabled = true;
form.ADGpanel.Visible = false;
form.CalfVarGroupBox.Enabled = false;
}
and call it using this
as well:
private void CowTypeSelect_SelectedIndexChanged(object sender, EventArgs e)
{
if (CowTypeSelect.SelectedIndex == 0)
CowTypeDefaults.LactatingCow(this);
}
I think define a delegate can slove you question. Define a delegate base on you target method, and declare a public varable of that delegate in class Form, named it Degegate temporary. When Form frm = new Form(); use frm.Delegate receive target method, then execcute that delegate varable in you class Form 's event which you need. I'm answer you question on mobelphone, so I can't change code style, sorry
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.