How to access a dynamically created checkbox in Windows Form - c#

In form_load event I create three check boxes. Then with a button_click event I want to check the state of the check boxes, but they are not available in my if statement. I found this piece of code as an example:
CheckBox chk = new CheckBox();
chk.Top = 50;
chk.Left = 50;
chk.Text = "Check Box Test";
chk.Name = "chkTest";
this.Controls.Add(chk);
CheckBox chkTest = (CheckBox)Controls["chkTest"];
which works only if I check the state inside the form_load. How do I access the check boxes with a button_click?

An option would be to create a List<CheckBox> at the class level to hold a collection of the checkboxes you create.
Example:
List<CheckBox> CheckBoxes = new List<CheckBox>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
CreateCheckBoxes();
}
private void CreateCheckBoxes()
{
//Create 3 checkboxes
int intialTop = 50;
for (int i = 0; i < 3; i++)
{
CheckBox chk = new CheckBox();
chk.Top = intialTop;
chk.Left = 50;
chk.Text = "Check Box Test";
chk.Name = "chkTest";
this.Controls.Add(chk);
CheckBoxes.Add(chk);
intialTop += 20;
}
//You can access your checkboxes anywhere in Form1 now.
var first = CheckBoxes.First();
first.Text = "First Checkbox";
}
Additional Example:
This example shows adding two checkboxes to the form as well as giving them their own click event handlers.
CheckBox checkBoxA;
CheckBox checkBoxB;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Add checkbox A
checkBoxA = new CheckBox();
checkBoxA.Top = 10;
checkBoxA.Left = 50;
checkBoxA.Text = "CheckBoxA";
//Register the event handler for this checkbox
checkBoxA.Click += new EventHandler(checkBoxA_Click);
this.Controls.Add(checkBoxA);
//Add checkbox B
checkBoxB = new CheckBox();
checkBoxB.Top = 30;
checkBoxB.Left = 50;
checkBoxB.Text = "checkBoxB";
//Register the event handler for this checkbox
checkBoxB.Click += new EventHandler(checkBoxB_Click);
this.Controls.Add(checkBoxB);
}
void checkBoxA_Click(object sender, EventArgs e)
{
MessageBox.Show("CheckBoxA has been clicked!!!");
}
void checkBoxB_Click(object sender, EventArgs e)
{
MessageBox.Show("CheckBoxB has been clicked!!!");
}

As stated earlier, you can create a class level CheckBox and then check that anywhere you need to in your code:
CheckBox checkBox1 = new CheckBox();
private void Form1_Load()
{
checkBox1.Name = "CheckBox1";
checkBox1.Text = "Click Me!";
checkBox1.Click += new EventHandler(checkBox1_Click); // Only need this if you want a click handler
this.Controls.Add(checkBox1);
}
private void checkBox1_Click(object sender, EventArgs e)
{
MessageBox.Show("You click the check box");
}
private void submitButton_Click(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
MessageBox.Show("Check box is checked!");
}
}
Alternatively, you can iterate over the form's controls and search for the check boxes there:
private void CheckCheckBoxes(string checkBoxName)
{
// this.Controls is a collection of all controls on the form (assuming this is run on the Form class)
foreach(Control control in this.Controls)
{
if (control.Name == checkBoxName && control is CheckBox)
{
CheckBox checkBox = control as CheckBox;
if (checkBox.Checked)
{
MessageBox.Show("Check box is checked");
}
}
}
}

Related

Use Panel.Click (of Dynamic Panels) event on Button.Click C# Windows Forms

I have Dynamically generated panels on my Form, every panel has multiple controls including TextBoxes, ComboBoxes and Buttons. I want to catch their values on a "Save" Button which is not dynamically generated (its in the form). I'm getting the Values with this code:
private void GetPanelControls(object sender, EventArgs e)
{
Panel allpanels = sender as Panel;
panelname = ItemsIDSelected[panelnamecounter] + "p";
//"p" identifies Panel and there is a counter with a list
if (allpanels.Name == panelname)
{
foreach (Control item in allpanels.Controls)
{
if (item.Name == (ItemsIDSelected[panelcontrolcounter] + "t")) //"t" identifies TextBox
{
ItemsNameListforInsert.Add(item.Text);
panelcontrolcounter++; //Panel has multiple controls
}
panelnamecounter++; //There are multiple Panels
}
}
}
How can I call this event on my Button_Click Event??
Panel panelGroup = new System.Windows.Forms.Panel();
panelGroup.Click += new EventHandler(GetPanelControls);
This is how Im Generating Panels and its event.
you can try something like this
private void Button_Click(object sender, EventArgs e)
{
GetPanelControls(this, new EventArgs());
}
EDIT
What if we use a method for this without using panel click event, if you need you can call this method inside the panel click event
private void GetPanelControls()
{
foreach (Control formControl in this.Controls)
{
if (formControl is Panel)
{
string panelName = ItemsIDSelected[panelnamecounter] + "p";
if (formControl.Name == panelName)
{
foreach (Control item in formControl.Controls)
{
// Your Code
}
}
}
}
}
//Control create button
private void button1_Click(object sender, EventArgs e)
{
Panel pnl = new Panel();
pnl.Name = "pnltest";
pnl.Location = new Point(500, 200);
TextBox txt1 = new TextBox();
txt1.Name = "txttest";
txt1.Location = new Point(0 ,10);
pnl.Controls.Add(txt1);
ComboBox cmb = new ComboBox();
cmb.Location = new Point(0, 50);
cmb.Name = "cmbtest";
cmb.Items.Add("one");
cmb.Items.Add("two");
cmb.Items.Add("three");
pnl.Controls.Add(cmb);
Button btn = new Button();
btn.Name = "btntest";
btn.Text = "submit";
btn.Location = new Point(0, 75);
btn.Click += btn_Click;
pnl.Controls.Add(btn);
this.Controls.Add(pnl);
}
//control button click event
void btn_Click(object sender, EventArgs e)
{
foreach (Control frmcntrl in this.Controls)
{
if (frmcntrl is Panel)
{
if (frmcntrl.Name == "pnltest")
{
foreach (Control item in frmcntrl.Controls)
{
if (item is TextBox)
{
if (item.Name == "txttest")
{
MessageBox.Show(item.Text .ToString());
}
}
else if (item is ComboBox)
{
if (item.Name == "cmbtest")
{
MessageBox.Show(item.Text);
}
}
}
}
}
}
}

How to make one event to identify whether multiple radio buttons are checked?

I have the following code which checks each radio button (Temp30, Temp40 and Temp60) and does the necessary things such as turning the wash temperature light on etc...
I want to create an event which handles all 3 radio buttons. I thought it could possibly have something to do with the groupbox they are in? (it is called TempGroupBox)
Any help would be much appreciated!
private void Temp30_CheckedChanged(object sender, EventArgs e)
{
if (Temp30.Checked)
{
MainDisplayLabel.Text = (" SELECT SPIN SPEED");
WashTempLight.Visible = true;
WashTempLight.Image = Properties.Resources._30degrees;
SpeedGroupBox.Enabled = true;
}
}
private void Temp40_CheckedChanged(object sender, EventArgs e)
{
if (Temp40.Checked)
{
MainDisplayLabel.Text = (" SELECT SPIN SPEED");
WashTempLight.Visible = true;
WashTempLight.Image = Properties.Resources._40degrees;
SpeedGroupBox.Enabled = true;
}
}
private void Temp60_CheckedChanged(object sender, EventArgs e)
{
if (Temp60.Checked)
{
MainDisplayLabel.Text = (" SELECT SPIN SPEED");
WashTempLight.Visible = true;
WashTempLight.Image = Properties.Resources._60degrees;
SpeedGroupBox.Enabled = true;
}
}
You can bind all radioButton's event to the same handler and use sender parameter to get the control that the action is for.
private void Temps_CheckedChanged(object sender, EventArgs e)
{
string checkedName = ((RadioButton)sender).Name;
if(checkedName == "Temp40")
{
...
}
else if(checkedName == "Temp60")
{
...
}
}
You can add event handler for all RadioBUttons's like that after InitializeComponent():
var radioButtons =this.Controls.OfType<RadioButton>();
foreach (RadioButton item in radioButtons)
{
item.CheckedChanged += Temps_CheckedChanged;
}

How to handle events of dynamically added checkbox on windows form

I am able to add checkbox dynamically on windows form and add data value to its text property. On click of any checkbox I have run a procedure which will make certain other checkbox disabled.
I am not able to find eventhandler for it.
Have you tried this
CheckBox check = new CheckBox();
check.Checked = true;
check.AccessibleName = checkName;
check.Location = new System.Drawing.Point(340, 40);
check.CheckedChanged +=new EventHandler(check_CheckedChanged);
this.Controls.Add(check);
private void custom_event_handler(object sender, EventArgs e)
{
....
}
and then you add checbox like this:
CheckBox cb = new CheckBox();
cb.CheckedChanged += new EventHandler(custom_event_hahndler);
if the name of the dynamically added checkbox is c, the answer is as below:
c.CheckedChanged += c_CheckedChanged;
and c_CheckedChanged is as below:
private void c_CheckedChanged(object sender, EventArgs e)
{
if (((CheckBox)sender).Checked)
{
((CheckBox)(this.Controls.Find("c1", false))[0]).Enabled = false;
}
}
which c1 is the name of the checkbox you want to disable.
Add event handler when you create a checkbox programmatically. And its handler you can do your code logic.
CheckBox dynamicCheckBox = new CheckBox();
dynamicCheckBox.CheckedChanged +=new EventHandler(dynamicCheckBox_CheckedChanged);
private void dynamicCheckBox_CheckedChanged(object sender, EventArgs e)
{
// Your code
}

Find Control() not working

I have created 5 text boxes in a button click event and i have to get the values in the text boxes when the dynamically generated button is clicked.
protected void Button1_Click(object sender, EventArgs e)
{
for(int i=0;i<5;i++)
{
HtmlGenericControl tr = new HtmlGenericControl("tr");
HtmlGenericControl td = new HtmlGenericControl("td");
HtmlGenericControl tdbtn = new HtmlGenericControl("td");
TextBox txt=new TextBox();
txt.ID="txt_"+i.ToString();
td.Controls.Add(txt);
Button btn=new Button();
btn.ID="btn_"+i.ToString();
btn.Click+=new EventHandler(btnpay_Click);
btn.Text="Pay";
tdbtn.Controls.Add(btn);
tr.Controls.Add(td);
tr.Controls.Add(tdbtn);
PlaceHolder1.Controls.Add(tr);
}
}
But i couldn't get the Values in the text boxes at btnpay_Click
protected void btnpay_Click(object sender, EventArgs e)
{
Button btn = new Button();
btn = sender as Button;
string[] splitvaues = btn.ID.Split('_');
string identity = splitvaues[1];
TextBox txt = new TextBox();
txt =PlaceHolder1.FindControl("txt_" + identity) as TextBox;
}
Can Anybody tell me a way to solve this problem?
Your problem is that FindControl doesn't recurse down the control tree. It only searches the controls directly in the ControlCollection of the container.
This method will find a control only if the control is directly
contained by the specified container; that is, the method does not
search throughout a hierarchy of controls within controls.
You need to write a recursive FindControl. Something like:
public static Control FindControlRecursive(this Control control, string id)
{
if (control == null || control.ID == id) return control;
foreach (var c in control.Controls)
{
var found = c.FindControlRecursive(id);
if (found != null) return found;
}
return null;
}
try this code.....
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
createcontrol();
}
}
private void createcontrol()
{
for (int i = 0; i < 5; i++)
{
HtmlGenericControl tr = new HtmlGenericControl("tr");
HtmlGenericControl td = new HtmlGenericControl("td");
HtmlGenericControl tdbtn = new HtmlGenericControl("td");
TextBox txt = new TextBox();
txt.ID = "txt_" + i.ToString();
td.Controls.Add(txt);
Button btn = new Button();
btn.ID = "btn_" + i.ToString();
btn.Click += new EventHandler(btnpay_Click);
btn.Text = "Pay";
tdbtn.Controls.Add(btn);
tr.Controls.Add(td);
tr.Controls.Add(tdbtn);
plh1.Controls.Add(tr);
}
}
protected void btnpay_Click(object sender, EventArgs e)
{
Button btn = new Button();
btn = sender as Button;
string[] splitvaues = btn.ID.Split('_');
string identity = splitvaues[1].ToString();
TextBox txt = new TextBox();
txt = plh1.FindControl("txt_" + identity) as TextBox;
string q = txt.Text;
}
protected void Button1_Click(object sender, EventArgs e)
{
createcontrol();
}

How do I pass a value from dynamic generated combobox to the next form's combobox?

I am making a windows form project and facing difficulty in passing the dynamically generated control value to the other form's normal control value.
My code is:
int c = 0;
int p = 0;
private void button1_Click(object sender, EventArgs e)
{
panel1.VerticalScroll.Value = VerticalScroll.Minimum;
// panel1.HorizontalScroll.Value = HorizontalScroll.Minimum;
ComboBox txtRun3 = new ComboBox();
txtRun3.Name = "txtDynamic" + c++ ;
txtRun3.Location = new Point(30, 18 + (30 * c))
panel1.Controls.Add(txtRun3);
txtRun3.Focus();
}
private void button2_Click(object sender, EventArgs e)
{
Form4 f4 = new Form4();
Button bt = sender as Button;
ComboBox cb2 = bt.Tag as ComboBox;
f4.Combo.Text = bt.Text;
}
I am getting the error:
"Object reference not set to an instance of an object."
Provide a public property in the Form4
public ComboBox Combo
{
get
{
return this.comboBox1;
}
set
{
this.comboBox1 = value;
}
}
Then you can access it in this way:
Form4 f4 = new Form4();
Button bs = (Button) sender;
f4.Combo.Text = bs.Text;

Categories

Resources