Controlling Dynamic Checkbox in C# - c#

My task is to read entries from a database and put a Checkbox corresponding to each entry
I have opened a database connection and have created the checkboxes but am unable to check the setting of the checkbox. I am storing my checkboxes using a static array ck[]
int count = 0;
while(dr.Read()) //Reading the Database
{
CheckBox temp = new CheckBox(); //Creating a temprory checkbox
temp.Text = dr[1].ToString();
temp.Checked = false; //Making the checkbox intitally empty
temp.ID = dr[0].ToString();
ck[count] = temp; //inserting the checkbox's references into the array
ck[count].CheckedChanged += new EventHandler(temp_CheckedChanged); //Adding the even handler
Panel1.Controls.Add(ck[count]); //Adding the checkbox to panel
LiteralControl lc = new LiteralControl("<br>");
Panel1.Controls.Add(lc);
count++;
}
void temp_CheckedChanged(object sender, EventArgs e) //handling the checking and unchecking of the checkbox
{
CheckBox ckb = (CheckBox)sender;
ck[index].Checked = !ck[index].Checked;
}
The problem arises in the fact that there is no update in the .Checked entry of the checkboxes.
I have read many posts here and tried to implement them too but nothing has worked out so far. I have even tried reading the data from the pane on which I am showing it in.

Better to use checkboxlist. Because you can add items at run time and works like list.

Related

DataGridView not displaying changes to checkbox when application is launched

I have the following code that will create a checkbox column, insert as first column to the main data grid, and then loop through the rows to set the checkbox to checked. Basically, what I'm trying to do is add checkboxes that are checked by default when the application launches.
The issue is that when the application is started, the checkboxes remain untouched. I've added the ToolTip text below to see whether that takes effect, but no luck there.
I also added an event that will trigger the same code below (calling the same method), and it will refresh the grid with the checkboxes CHECKED.
DataGridViewCheckBoxColumn importSelectionColumn = new DataGridViewCheckBoxColumn();
importSelectionColumn.Name = "dataSelection";
importSelectionColumn.DisplayIndex = 0;
importSelectionColumn.HeaderText = "\u2611";
importSelectionColumn.Width = 35;
importSelectionColumn.Visible = true;
importSelectionColumn.FalseValue = false;
importSelectionColumn.TrueValue = true;
importSelectionColumn.HeaderCell.Style.Font = new Font(FontFamily.GenericSansSerif, 16f);
// Add column to grid:
mainDataGrid.Columns.Insert(0, importSelectionColumn);
// Set checkbox to true for all rows:
foreach (DataGridViewRow row in this.mainDataGrid.Rows)
{
row.Cells["dataSelection"].Value = true;
// Adding this just to see whether it's set when application starts.
row.Cells["dataSelection"].ToolTipText = "Testing";
}
mainDataGrid.RefreshEdit();
mainDataGrid.Refresh();
Make sure that the code that changes state is not being executed too early.
It should be executed after Loaded event of the container form, when all controls are loaded and ready for work.
Adding a check box control to your mainDataGrid can be done in DataBound event instead of on page load event.
Try to use below code on your page and check:
protected void mainDataGrid_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow objRow in mainDataGrid.Rows)
{
TableCell tcCheckCell = new TableCell();
CheckBox chkCheckBox = new CheckBox();
tcCheckCell.Controls.Add(chkCheckBox);
objRow.Cells.AddAt(0, tcCheckCell);
}
}

How to access dynamically created controls in C#?

I have dynamically created checkbox's. I have an option "Select All". How do I select all the dynamically created checkboxes in C#?
How to select all the dynamic checkboxes which have been created?
protected void chkbox_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkBtn = new CheckBox();
chkBtn = sender as CheckBox;
selectedTypeId.Add(Convert.ToInt16(chkBtn.Name));
foreach(int id in selectedTypeId)
{
Console.WriteLine(id);
}
}
Declare a global List of CheckBoxes:
List<CheckBox> boxes;
And on your program start instantiate it.
boxes = new List<CheckBox>();
Each time you dynamically add a CheckBox, also add it to your List.
CheckBox chkBtn = new CheckBox();
boxes.Add(chkBtn);
When you want to check them all at once, use a loop to go through the list.
foreach(CheckBox box in boxes)
box.Checked = true;
You can get all of the CheckBoxes of the control like so:
var checkBoxes = this.Controls.OfType<CheckBox>();
checkBoxes.ToList()?.ForEach(x=>x.Checked = true);
But typically you would put all of the checkboxes in groupbox (from ux perspective)
groupBox.Controls.Add(checkBox);
and then get them from the groupbox:
var checkBoxes = groupBox.Controls.OfType<CheckBox>();

DataGridViewComboBoxCell failing to retain choice, auto-selecting item at '0' th index of collection

As clear from the title, my datagridviewComboboxCell, which I am adding to selected cells only, are showing it's dropdown list perfectly, and I can select them seamlessly. Problem arises when the combobox losses focus, it forgets everything about selected item and auto selects the item at index 0, of it's range collection. And many time, a 'DataGridViewDataErrorEvent' is occuring(I traced it by adding DataError event handler). I can not understand what is going wrong to cause the error to fire. Moreover even though I daclare
e.Cancel = false;
in the eventhandler, the ComboBox auto-selects item at index 0.
Plese help me out of this.
N.B . I forgot to add initially(when it appears to screen!), the DataGridViewComboBox has no item selected.
EDIT:-
Code snippet
//Creating and Adding propertiesof DataGridViewComboBoxCell.
RegViewdataGridView.Rows[uniqcustCount].Cells[day].ReadOnly = false; //uniqcustCount & day Are Integers
var pcmbcell = new DataGridViewComboBoxCell();
var tcmbcell = new DataGridViewComboBoxCell();
RegViewdataGridView[day,uniqcustCount] = pcmbcell;
pcmbcell.ReadOnly = false;
pcmbcell.DropDownWidth = 80;
pcmbcell.DataSource = shipdPrdLst;
pcmbcell.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox;
RegViewdataGridView.DataError += RegViewdataGridView_DataError;
void RegViewdataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
e.Cancel = false;
}

Checking if the Checkbox is checked or not dynamically in c#

I have created a Checkbox dynamically by this button code
private void btn_add_record_Click(object sender, EventArgs e)q2
{
CheckBox DeleteCheckBox = new CheckBox();
Point P_request = new Point(nXCheckBox, nYCheckBox);
DeleteCheckBox.Location = P_request;
DeleteCheckBox.Name = "CH"+Record_ID+"";
}
Then i Checked it manually
Then i need to check a specific checkbox its name is "CH"+Record_ID+" to be checked or not dynamically using this code
string ChechBoxName = "CH1";
CheckBox DeleteChechBox = new CheckBox();
DeleteChechBox.Name = ChechBoxName;
if (DeleteChechBox.Checked)
{
// To Do Code
}
When i debug this code, it doesn't enter the if statement .. WHY ?
You're checking if the box is checked before it gets checked. Add
DeleteChechBox.CheckedChanged += DeleteChechBoxCheckedChanged;
and add the method DeleteChechBoxCheckedChanged where you can test whether or not it's been checked. You can also use
DeleteChechBox.Checked = true;
to check the box through code.
Edit:
To get a certain checkbox by it's name you have to either store it as a global variable or look through the controls array in the form.
foreach (Control control in this.Controls)
{
if (control.Name == "CH1")
{
CheckBox DeleteChechBox = (CheckBox)control;
if (DeleteChechBox.Check)
{
//To Do Code
}
}
}
When you create a new CheckBox, the default Checked value is false. Therefore if (DeleteChechBox.Checked)
returns false which is why you don't enter the block. You're not checking any existing Checkboxes, you're checking the new one you created.
In WPF you can accomplish it like shown in the following code snippet (pertinent to your example):
string _strCheckBoxName = "CH1";
CheckBox DeleteCheckBox= new CheckBox();
DeleteCheckBox.Name = _strCheckBoxName ;
DeleteCheckBox.Checked+=(s,e)=>CheckBox_Change(s,e);
DeleteCheckBox.Unchecked+=(s,e)=>CheckBox_Change(s,e);
DeleteCheckBox.IsChecked = true;
private void CheckBox_Change(object sender, RoutedEventArgs e)
{
if ((sender as CheckBox).Name=_strCheckBoxName && (bool)(sender as CheckBox).IsChecked)
{
// To Do Code
}
}
In suggested solution, you essentially subscribe the newly created CheckBox control to a single event handler proc, which looks at the control name and if checked runs some code. If more CheckBox added, then use the same event-subscription technique pointed to the same handler, and extend it with another if statement (or if-else if, or switch statement).
Hope this will help. Rgds,
Your problem is that you are creating one CheckBox in your btn_add_record_Click handler and then creating a new one in your second code fragment, which just happens to have the same Name as the first. That notwithstanding, it is not the same check box, so will not have the same value for its Checked property.
The way to fix that is to create the checkbox in the form's constructor as a class member, and then discover it when you need it by searching the components, using the code which Xylorast showed:
foreach (Control control in this.Controls)
{
if (control.Name == "CH1")
{
CheckBox DeleteChechBox = (CheckBox)control;
if (DeleteChechBox.Check)
{
//To Do Code
}
}
}
This is what I meant. Maybe you already checked it..?
string ChechBoxName = "CH1";
CheckBox DeleteChechBox = new CheckBox();
DeleteChechBox.Name = ChechBoxName;
DeleteChechBox.Checked = true;
if (DeleteChechBox.Checked)
{
// To Do Code
}
Edit:
Here is another way of accessing the control instead of enumerating over all the controls on the form for each control you would like to access:
Dictionary<string, CheckBox> checkBoxCollection = new Dictionary<string, CheckBox>();
And in your method where you create the checkbox add it to the dictionary:
checkBoxCollection.Add("CH1",DeleteCheckBox);
Access the checkbox from wherever you want like this:
CheckBox checkBox;
bool success = controls.TryGetValue("CH1"), out checkBox);
if (success)
{
// To Do Code
}
Or in your CheckedEvent you can get the CheckBox being checked like this:
CheckBox checkBox = sender as CheckBox;

Dynamically creating checkboxes from an array and then iterate through them to check for selected

I have been creating a list of checkboxes from returned information from a webservice. The checkboxes render as expected but when I try and then read them to check if they have been selected the code cannot find them.
I have created a panel called planList and had the code loop creating the dynamic list of boxes - then on a button being pressed it should iterate through the list of checkboxes to see if the user has selected any values. The code doesn't seem to be picking up any checkboxes unless created dynamically. Anyone able to assist? At the moment I am just trying to pull out the ID if it picks up a checkbox
Code:
planList.Controls.Add(new LiteralControl("<h2>Plan List </h2>"));
foreach (string[] ar in ws.planS(this.txtGetDetails.Text)) {
CheckBox cb = new CheckBox();
cb.Text = ar[1].ToString();
cb.ID = ar[0];
planList.Controls.Add(cb);
planList.Controls.Add(new LiteralControl("<b> Application ID: " + ar[2] + "</b>"));
planList.Controls.Add(new LiteralControl("<br>"));
}
protected void Uploadbutton_Click1(object sender, System.EventArgs e) {
foreach (Control c in planList.Controls) {
CheckBox chx = c as CheckBox;
if (chx != null) {
var planid = c.ID;
}
}
}
You have to override the CreateChildControls method and add the checkboxes there. With this, you are creating the controls tree before loading the ViewState, which contains the data of which one was checked.

Categories