Control C# checkbox using variable - c#

I have this code:
// code above
checkBox1.Checked = false;
checkBox2.Checked = false;
checkBox3.Checked = false;
checkBox4.Checked = false;
checkBox5.Checked = false;
checkBox6.Checked = false;
checkBox7.Checked = false;
checkBox8.Checked = false;
checkBox9.Checked = false;
//code below
I have 320 checkBoxes to set cleared/false.
How do I control checkBox(variable)?
I would like to do the following:
for (int counter=1; counter<321; counter++)
{
checkBox***Put counter Variable Here***.Checked = false;
}

If all the checkboxes are incremental, then you can use the Control.ControlCollection.Find Method.
for (int counter=1; counter<321; counter++)
{
var ctrl = this.Controls.Find("checkbox" + counter, true).FirstOrDefault() as CheckBox;
if (ctrl != null)
{
ctrl.Checked = false;
}
}
If you just want to set every checkbox, then filter the Controls collection:
var checkBoxes = this.Controls.OfType<CheckBox>();
foreach (CheckBox cbx in checkBoxes)
{
cbx.Checked = false;
}

You can loop through all of the controls on the form and check for check boxes.
foreach (Control ctrl in Controls)
{
if (ctrl is CheckBox)
{
((CheckBox)ctrl).Checked = false;
}
}

void SetAllCheckBoxesState(Boolean isChecked) {
foreach(Control c in this.Controls) {
CheckBox cb = c as CheckBox;
if( cb != null ) cb.Checked = isChecked;
}
}

Related

Turn textboxes and buttons visible when the number of tracks it's selected in a combobox

I'm trying to turn textboxes and buttons visible when the number of tracks it's selected in a combobox.
For example: when I select 3, just 3 textboxes and the 3 respective buttons to select the tracks are enabled. How can I change this code that I've made to a simple foreach or a for?
if (numero_faixas == 1) {
txtFaixa1.Visible = true;
btnFaixa1.Visible = true;
} else if (numero_faixas == 2) {
txtFaixa1.Visible = true;
btnFaixa1.Visible = true;
txtFaixa2.Visible = true;
btnFaixa2.Visible = true;
} else if (numero_faixas == 3) {
txtFaixa1.Visible = true;
btnFaixa1.Visible = true;
txtFaixa2.Visible = true;
btnFaixa2.Visible = true;
txtFaixa3.Visible = true;
btnFaixa3.Visible = true;
}
You can reduce the lines of code by changing your conditions, so you don't have to reference the same control so many times:
if (numero_faixas > 0)
{
txtFaixa1.Visible = true;
btnFaixa1.Visible = true;
}
if (numero_faixas > 1)
{
txtFaixa2.Visible = true;
btnFaixa2.Visible = true;
}
if (numero_faixas > 2)
{
txtFaixa3.Visible = true;
btnFaixa3.Visible = true;
}
To use a foreach loop, you could cast the Controls collection to an IEnumerable<Control> and then, using System.Linq;, you can filter on controls of type TextBox and Button, where the control name contains "Faxia". Then, in the loop body, we can use int.TryParse to try to convert the last character of the control name to an int, and if that succeeds, then set the control to Visible if the control number is less than numero_faixas + 1:
foreach (Control control in Controls.Cast<Control>()
.Where(c => (c is Button || c is TextBox) && c.Name.Contains("Faixa")))
{
// Get the number associated with this control and compare it to numero_faixas
int controlNumber;
if (int.TryParse(control.Name.Substring(control.Name.Length - 1), out controlNumber) &&
controlNumber < numero_faixas + 1)
{
control.Visible = true;
}
}
Here's a proof of concept that you could respin using your business rules.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace ShowHideButtons_47439046
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
InitOurThings();
}
private void InitOurThings()
{
//lets create a combo box with options to select
ComboBox combo = new ComboBox();
combo.Location = new Point(5, 5);//place it somewhere
//add selectable items
for (int i = 0; i < 10; i++)
{
combo.Items.Add(i);
}
combo.SelectedValueChanged += Combo_SelectedValueChanged;//the event which will handle the showing/hidding
Controls.Add(combo);//add the combo box to the form
//lets create some buttons and textboxes
int btnx = 5;
int btny = combo.Height + combo.Location.Y + 5;
for (int i = 0; i < 10; i++)
{
Button btn = new Button();
btn.Location = new Point(btnx, btny);
btn.Name = i.ToString();
btn.Text = i.ToString();
Controls.Add(btn);
btny += btn.Height + 5;
TextBox txtbx = new TextBox();
txtbx.Location = new Point(btn.Location.X + btn.Width + 5, btn.Location.Y);
txtbx.Name = i.ToString();
txtbx.Text = i.ToString();
Controls.Add(txtbx);
}
}
private void Combo_SelectedValueChanged(object sender, EventArgs e)
{
int selectedValue = int.Parse(((ComboBox)sender).SelectedItem.ToString());
foreach (Control item in Controls)
{
//show/hide the controls based on their Name being Equal Or Smaller than the selectedItem
if (item is TextBox)
{
int itemNumber = int.Parse(item.Name);
item.Visible = itemNumber <= selectedValue ? true : false;
}
if (item is Button)
{
int itemNumber = int.Parse(item.Name);
item.Visible = itemNumber <= selectedValue ? true : false;
}
}
}
}
}

DatagridView Checkbox Column is always null

I have a strange issue.
Basically I have a datagridview and a button. When I click this button it checks all rows for column 1s value - the checkbox column. It then sets it to true / false depending on what it currently is.
Thats all fine.
But then, I have another button to do something with these rows that are ticked. I click it and it only ever identifies the first row as being ticked. The rest are apparently null now..?
So, how can I programmtically set the value of a checkbox column in a datagrid view and then read it again cause Im apparently way off the mark based on my results.
This sets the tick boxs and I can see them, untick them manually etc.
foreach (DataGridViewRow row in dgv.Rows)
{
var ch1 = new DataGridViewCheckBoxCell();
ch1 = (DataGridViewCheckBoxCell)row.Cells[0];
if (ch1.Value == null)
ch1.Value = false;
switch (ch1.Value.ToString())
{
case "True":
ch1.Value = false;
break;
case "False":
ch1.Value = true;
break;
}
}
Then the next button to check values is just finding nulls
foreach (DataGridViewRow row in rows)
{
var ch1 = new DataGridViewCheckBoxCell();
ch1 = (DataGridViewCheckBoxCell)row.Cells[0];
if (ch1.Value == null)
ch1.Value = false;
switch (ch1.Value.ToString())
{
case "True":
ch1.Value = true;
break;
case "False":
ch1.Value = false;
break;
}
var val = row.Cells["EbayListingID"].Value.ToString();
if (ch1.Value.ToString() == "true") continue;
var listing = dsEntities.EbayListings.First(x => x.EbayListingID.ToString() == val);
SubmitListingForReview(listing, false);
}
First,
if (ch1.Value.ToString() == "true") continue;
Why is string constant is "true", but not "True"?
Second, in the next button click handler, what is it "rows"?
foreach (DataGridViewRow row in rows)
I try this code and it works fine :
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var ch1 = new DataGridViewCheckBoxCell();
ch1 = (DataGridViewCheckBoxCell)row.Cells[0];
if (ch1.Value == null)
ch1.Value = false;
switch (ch1.Value.ToString())
{
case "True":
ch1.Value = false;
break;
case "False":
ch1.Value = true;
break;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var ch1 = new DataGridViewCheckBoxCell();
ch1 = (DataGridViewCheckBoxCell)row.Cells[0];
if (ch1.Value == null)
ch1.Value = false;
switch (ch1.Value.ToString())
{
case "True":
ch1.Value = true;
break;
case "False":
ch1.Value = false;
break;
}
var val = row.Cells[1].Value;
if (ch1.Value.ToString() == "True") continue;
MessageBox.Show("1");
}
}

how to check whether checkbox is checked in datagridview column

I have a Datagridview within a windows form which loads data. I have also included a checkbox column to this Datagridview in run time. My question is how can i know if any of the checkboxs from the checkbox column has been checked, and if a checkbox has been checked enable a button. I have used CellValueChanged event to perform above task but unable to get the desired result.
This is what i have done
List<int> ChkedRow = new List<int>();
for (int i = 0; i <= Datagridview1.RowCount - 1; i++)
{
if (Convert.ToBoolean(Datagridview1.Rows[i].Cells["chkcol"].Value) == true)
{
button1.Enabled = true;
}
else
{
button1.Enabled = false;
}
}
set false before the loop
button1.Enabled = false;
when you found checked item, set it as Enabled true and break the loop
button1.Enabled = true;
break;
code:
button1.Enabled = false;
for (int i = 0; i <= Datagridview1.RowCount - 1; i++)
{
if (Convert.ToBoolean(Datagridview1.Rows[i].Cells["chkcol"].Value))
{
button1.Enabled = true;
break;
}
}
Or you can do below as well
button1.Enabled = false;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell cell = row.Cells[colCheckIndex] as DataGridViewCheckBoxCell;
if (cell.Value == cell.TrueValue){
button1.Enabled = true;
break;
}
}
Try this code
button1.Enabled = false;
foreach (DataGridViewRow row in Datagridview1.Rows)
{
if (((DataGridViewCheckBoxCell)row.Cells["chkcol"]).Value)
{
button1.Enabled = true;
break;
}
}
or
//This will always call the checking of checkbox whenever you ticked the checkbox in the datagrid
private void DataGridView1_CellValueChanged(
object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == [Your column index])
CheckForCheckedValue();
}
private void CheckForCheckedValue()
{
button1.Enabled = false;
foreach (DataGridViewRow row in Datagridview1.Rows)
{
if (((DataGridViewCheckBoxCell)row.Cells["chkcol"]).Value)
{
button1.Enabled = true;
break;
}
}
}
NOTE
Don't forget to check the for Null value and do something if it is NULL

How to find label controls in an asp.net page

I have some label controls in a panel with id ResultsPanel. To find the label controls on the page, I did the following:
for (int ctr = 0; ctr < lblString.Length - 1; ctr++)
{
//string labelID = string.Format("lblResult{0}", ctr);
int mylbl = ctr + 1;
string lblResult = ((Label)ResultsPanel.FindControl("lblResult" + mylbl.ToString())).Text;
lblResult = lblString[mylbl].ToString();
}
lblResult1.Text = lblString.ToString();
lblString is a stringBuilder Object with 24 numbers. The Idea is to map each of the numbers in the stringbuilder object to labels in this manner:
lblResult1.Text = lblString[mylbl].ToString(); to the 24th label. But I can't seem to generate the labels and map the values to the label control.
Change the line to
Label lblResult = ((Label)ResultsPanel.FindControl("lblResult" + mylbl.ToString()));
lblResult.Text = lblString[mylbl].ToString();
Your question and code are a bit misleading, but I will try my best anyway.
Your code:
for (int ctr = 0; ctr < lblString.Length - 1; ctr++)
{
//string labelID = string.Format("lblResult{0}", ctr);
int mylbl = ctr + 1;
string lblResult = ((Label)ResultsPanel.FindControl("lblResult" + mylbl.ToString())).Text;
lblResult = lblString[mylbl].ToString();
}
lblResult1.Text = lblString.ToString();
If you have labels in the order of label1, label2, label3 ... then I would write something like this:
private void MapLabels()
{
var labelsResult = string.Empty;
var labelString = "123456789";
for (int i = 0; i < labelString.Length; i++)
{
var control = this.FindControl("label" + labelString[i]);
if(control != null)
{
labelsResult += ((Label)control).Text;
}
}
labelResult1.Text = labelsResult;
}
Let me know if you get stuck.
Hope this will help you. Like this you can get the value of label too.
public void GetControlsValuePopulated(Control control, Type controlType, Dictionary<string, string> dictControlPageValParam)
{
try
{
if (control.HasControls())
{
GetControlsValuePopulated(control, controlType, dictControlPageValParam);
}
else
{
if (controlType == null || controlType.IsAssignableFrom(control.GetType()))
{
if (control.ID != null)
{
bool FoundControl = dictControlPageValParam.ContainsKey(control.ID.Substring(3));
if (FoundControl)
{
switch (control.GetType().ToString())
{
case "System.Web.UI.WebControls.TextBox":
TextBox txt = (TextBox)control;
txt.Text = dictControlPageValParam[txt.ID.Substring(3)];
break;
case "System.Web.UI.WebControls.CheckBox":
CheckBox chk = (CheckBox)control;
if (dictControlPageValParam[chk.ID.Substring(3)].ToUpper() == "TRUE" || dictControlPageValParam[chk.ID.Substring(3)].ToUpper() == "T")
{
chk.Checked = true;
}
else
{
chk.Checked = false;
}
break;
case "System.Web.UI.WebControls.DropDownList":
DropDownList ddl = (DropDownList)control;
//ddl.SelectedValue = dictControlPageValParam[ddl.ID.Substring(3)];
break;
case "System.Web.UI.WebControls.RadioButtonList":
RadioButtonList rbl = (RadioButtonList)control;
rbl.SelectedValue = dictControlPageValParam[rbl.ID.Substring(3)];
break;
case "System.Web.UI.WebControls.HiddenField":
HiddenField hdn = (HiddenField)control;
hdn.Value = dictControlPageValParam[hdn.ID.Substring(3)];
break;
}
}
}
}
}
}
catch (Exception)
{
throw;
}
}
public void GetChildControlsId(Control control, Type controlType)
{
try
{
if (control.HasControls())
{
GetChildControlsId(control, controlType);
}
else
{
if (controlType == null || controlType.IsAssignableFrom(control.GetType()))
{
///checking if control already existing in the collection
if (control.ID != null)
{
bool FoundControl = controlHt.ContainsKey(control.ID);
if (!FoundControl)
{
switch (control.GetType().ToString())
{
case "System.Web.UI.WebControls.TextBox":
TextBox txt = (TextBox)control;
controlTypeName = txt.ID;
controlTypeName = controlTypeName.Substring(3);
controlTypeValue = txt.Text;
if (dictControlValParam.ContainsKey(controlTypeName) == false)
{
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
else
{
dictControlValParam.Remove(controlTypeName);
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
break;
case "System.Web.UI.WebControls.CheckBox":
CheckBox chk = (CheckBox)control;
controlTypeName = chk.ID;
controlTypeName = controlTypeName.Substring(3);
controlTypeValue = chk.Checked.ToString();
if (dictControlValParam.ContainsKey(controlTypeName) == false)
{
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
else
{
dictControlValParam.Remove(controlTypeName);
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
break;
case "System.Web.UI.WebControls.DropDownList":
DropDownList ddl = (DropDownList)control;
controlTypeName = ddl.ID;
controlTypeName = controlTypeName.Substring(3);
controlTypeValue = ddl.SelectedValue.ToString();
if (dictControlValParam.ContainsKey(controlTypeName) == false)
{
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
else
{
dictControlValParam.Remove(controlTypeName);
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
break;
case "System.Web.UI.WebControls.RadioButtonList":
RadioButtonList rbl = (RadioButtonList)control;
controlTypeName = rbl.ID;
controlTypeName = controlTypeName.Substring(3);
controlTypeValue = rbl.SelectedValue.ToString();
if (dictControlValParam.ContainsKey(controlTypeName) == false)
{
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
else
{
dictControlValParam.Remove(controlTypeName);
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
break;
case "System.Web.UI.WebControls.HiddenField":
HiddenField hdn = (HiddenField)control;
controlTypeName = hdn.ID;
controlTypeName = controlTypeName.Substring(3);
controlTypeValue = hdn.Value;
if (dictControlValParam.ContainsKey(controlTypeName) == false)
{
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
else
{
dictControlValParam.Remove(controlTypeName);
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
break;
}
}
}
}
}
}
catch (Exception)
{
throw;
}
}

how to loop through some ASP.NET labels to set their attributes?

How do I do this in a loop.
protected void ddlTool_SelectedIndexChanged(object sender, EventArgs e)
{
lblTool1.Visible = false;
txtTool1.Visible = false;
lblTool2.Visible = false;
txtTool2.Visible = false;
lblTool3.Visible = false;
txtTool3.Visible = false;
lblTool4.Visible = false;
txtTool4.Visible = false;
lblTool5.Visible = false;
if (ddlTool.SelectedValue == "1")
{
lblTool1.Visible = true;
txtTool1.Visible = true;
}
if (ddlTool.SelectedValue == "2")
{
lblTool1.Visible = true;
txtTool1.Visible = true;
lblTool2.Visible = true;
txtTool2.Visible = true;
}
if (ddlTool.SelectedValue == "3")
{
lblTool1.Visible = true;
txtTool1.Visible = true;
lblTool2.Visible = true;
txtTool2.Visible = true;
lblTool3.Visible = true;
txtTool3.Visible = true;
}
if (ddlTool.SelectedValue == "4")
{
lblTool1.Visible = true;
txtTool1.Visible = true;
lblTool2.Visible = true;
txtTool2.Visible = true;
lblTool3.Visible = true;
txtTool3.Visible = true;
lblTool4.Visible = true;
txtTool4.Visible = true;
}
Instead of having a separate variable for each textbox and label, have a collection of them - whether that's a List<T> or an array or whatever.
Then you can do:
// Potentially use int.TryParse here instead
int visibleLabels = int.Parse(ddlTool.SelectedValue);
for (int i = 0; i < labels.Count; i++)
{
labels[i].Visible = (i < visibleLabels);
textBoxes[i].Visible = (i < visibleLabels);
}
(Alternatively use two loops, one to set some Visible properties to true, and one to set some to false.)
You can access a control by its name using
container.Controls["nameofcontrol"]
So technically, you could use this to lookup your control
(Untested code)
for(int index = 1; index <= Convert.ToInt32(ddlTool.SelectedValue); index++)
{
this.Controls["lblTool" + index.ToString()].Visible = true;
this.Controls["txtTool" + index.ToString()].Visible = true;
}
Use a UserControl for each set of connected controls and then enable/disable the UserControl instead of all the component controls. This is classic, basic modularization of your user interface.
Note that this will still require a little "redundant" code because you're working with an unusual UI paradigm by enabling up-to the ddlTool's selected value of your control. E.g., create your user control that contains a single Label and TextBox. Call it LabeledTextBox or something similar. Then you'd create a collection of your labeled text boxes and enable them up to int.Parse(ddlTool.SelectedValue) - 1.
foreach (Control ctrl in this.Controls)
{
int index = (int)ctrl.Name.Substring(ctrl.Name.Length - 1);
int maxIndex = (int)ddlTool.SelectedValue;
ctrl.Visible = (index <= maxIndex);
}
Here is an example with no error checking, but should match your code functionality.
protected void ddlTool_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedValue = int.Parse(ddlTool.SelectedValue.ToString());
for (int i = 1; i <= 4; ++i)
{
bool state = i <= selectedValue;
this.Controls["lblTool" + i.ToString()].Visible = state;
this.Controls["txtTool" + i.ToString()].Visible = state;
}
}

Categories

Resources