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;
Related
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);
}
}
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>();
I have a UWP app in C#. I have a Radio Button that the user can turn check or uncheck. It is checked by default and the user can uncheck it when they wish. However when they uncheck it the bool value for RadioButton.IsChecked never returns false making impossible for the user to then recheck the Radio Button if required. My code is below.
private void usingmltBtn_Click(object sender, RoutedEventArgs e)
{
if (RadioButton.IsChecked == true)
{
RadioButton.IsChecked = false;
i2cerrRec.Visibility = Visibility.Collapsed;
i2cerrTxt.Visibility = Visibility.Collapsed;
mltI2Cnck = 0;
}
else if (RadioButton.IsChecked == false)
{
RadioButton.IsChecked = true;
mlttempLbl.Text = "N/C";
}
}
Thanks for your help.
As other's have described, RadioButtons are designed to work in a group. This means that you will have multiple RadioButtons for a user to select from but they can only have one checked.
When a RadioButton is checked, it cannot be unchecked by the user by clicking it again without using a custom behaviour that checks if the user has tapped the RadioButton but this would not be recommended.
I suggest that you use the CheckBox for this particular functionality. You can even re-template a CheckBox control to look like a RadioButton if you wish.
Go through the url below
https://learn.microsoft.com/en-us/windows/uwp/controls-and-patterns/radio-button
You might wrong in XAML code!
Use this
private void usingmltBtn_Click(object sender, RoutedEventArgs e)
{
if (RadioButton.Checked == true)
{
RadioButton.Checked = false;
i2cerrRec.Visibility = Visibility.Collapsed;
i2cerrTxt.Visibility = Visibility.Collapsed;
mltI2Cnck = 0;
}
else if (RadioButton.Checked == false)
{
RadioButton.Checked = true;
mlttempLbl.Text = "N/C";
}
}
I can see 2 problems in here:
1- I might be wrong but the method you posted is triggered by a control whose name is usingltBtn (Not descriptive by the way) if this is the case you might be running this code with the trigger of another control.
2- Either the name of the RadioButton is usingltBtn or not you are not referencing the code to your control RadioButton is the name of a class not a specific control.
How to fix this? If the name of your control is usingltBtn use usingltBtn.IsChecked instead of RadioButton.IsChecked if not find the name of your control and use it
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.
I have some code that create a few components on the click of a button. Something like this.
CheckBox chk = new CheckBox();
chk.Top = 50;
chk.Left = 50;
chk.Text = "Check Box Test";
chk.Name = "chkTest"
this.Controls.Add(chk);
So how do I use this component. For example I tried this but got and error saying the component didn't exist. I just want to get their values.
if(chkTest.Checked)
{
//Do this
}
Please help.
Thanks in adv.
Either create a member variable in your class called chkTest that you can use later, or retrieve it on the fly from the Controls collection when needed, like so:
CheckBox chkTest = (CheckBox)Controls["chkTest"];
if(chkTest.Checked) {
// ...
}
If you only care about the control when it is checked or unchecked, use an event.
chk.Checked += new RoutedEventHandler(CheckBox_Checked);
chk.Unchecked += new RoutedEventHandler(CheckBox_Checked);
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
CheckBox chkBox = sender as CheckBox;
if (chkBox.IsChecked.Value)
{
// Do this...
}
}
Make sure to unsubscribe from the event handlers when you are finished with them.
You're referencing chkTest but you created chk.
You could declare the Checkbox as a member variable of your page. Then you would be able to access it more easily.
Class MyPage
{
CheckBox chkTest;
// then in page load
// chkTest = new CheckBox(); ...
}
if ((Controls.Items["chkTest"] as CheckBox).Checked)
{
// Do this
}
should work, but it's not pretty to look at. :)
You could declare it as a variable, then use it like you did:
CheckBox chkTest = Controls.Items["chkTest"] as Checkbox;
if (chkTest.Checked)
{
// Do this
}
Look on this handy page for ways to manipulate and access your Control's collection of items:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.controlcollection_members.aspx