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
Related
I'm looking for the method which returns a bool on whether or not a tab in a TabControl is selected. I would think there would be something like tabPage1.IsSelected() but there isn't. I found this: TabControl.SelectedTab Property However, this SelectedTab property is absent from my WinForms class for some reason. Not sure if it's been taken out or what. Thanks.
I tried below code to know which tab is selected.
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
if (tabControl1.SelectedTab == tabControl1.TabPages["operationstabPage"])
{
//add your code here
}
}
To get the selected tab in tab control, you can use -
var selectedTab = this.tabControl1.SelectedTab;
So you can do -
bool tabSelected = this.tabControl1.SelectedTab == this.tabPage1;
I have a c# winform with tabControl (it has 5 Tabs), textboxes, datetimepicker and checkboxes, connected via Entity Framework to a table.
All my checkboxes have their property Checked set to False, CheckState set to Unchecked and ThreeState set to False.
When I'm adding a new record, my checkboxes encounter a very strange behaviour. At adding a new record, my program calls a subroutine called EmptyCheckBoxes to make sure, that they are all set to false and their texts are set to "Ne". So far so good --> they are set to false and texts are correct(see image1).
Here are 2 scenarios with my problem:
1.
I click one checkbox to make him checked (set to true and set its text to "Da" --> look at Ponedeljek on image2). Till here, everything went as planned.
But, if I use my mouse and try click other checkbox (look at Torek on image3), this checkbox remains unchecked and all other checkboxes on my form have become grayed and checked!
2.
At adding a new record checkboxes are set to false and texts are correct(see image1). But, this time I'm not going to touch my checkboxes, I just click into my datetimepicker and then into some other textbox. Bam!
All checkboxes on my form have become grayed and checked!
How can this be, if their ThreeState property is set to False?
This is really annoying and I'm totaly lost, where to look to find the cause of this problem. Because, if I save this new record, all checkboxes lose their gray color and stay checked with texts "Ne" (values true are saved into table!).
All checkboxes have this code (this is from one of them):
private void checkBox49_Click(object sender, EventArgs e)
{
if (checkBox49.Checked == true)
{
checkBox49.Text = "Da";
}
else
{
checkBox49.Text = "Ne";
}
}
private void checkBox49_CheckedChanged(object sender, EventArgs e)
{
if (checkBox49.Checked == true)
{
checkBox49.Text = "Da";
}
else
{
checkBox49.Text = "Ne";
}
}
This is a code for setting checkboxes to false and texts to "Ne":
private void EmptyCheckBoxes()
{
TabPage tabPage1 = tabControl1.TabPages[0];
TabPage tabPage2 = tabControl1.TabPages[1];
TabPage tabPage3 = tabControl1.TabPages[2];
TabPage tabPage4 = tabControl1.TabPages[3];
TabPage tabPage5 = tabControl1.TabPages[4];
tabControl1.SelectedTab = tabPage1;
UncheckCheckBoxes(tabPage1);
tabControl1.SelectedTab = tabPage2;
UncheckCheckBoxes(tabPage2);
tabControl1.SelectedTab = tabPage3;
UncheckCheckBoxes(tabPage3);
tabControl1.SelectedTab = tabPage4;
UncheckCheckBoxes(tabPage4);
tabControl1.SelectedTab = tabPage5;
UncheckCheckBoxes(tabPage5);
}
private void UncheckCheckBoxes(Control ctrl)
{
CheckBox chkBox = ctrl as CheckBox;
if (chkBox == null)
{
foreach (Control child in ctrl.Controls)
{
UncheckCheckBoxes(child);
}
}
else
{
chkBox.Checked = false;
chkBox.Text = "Ne";
}
}
Thank you for any hint, clue or solution to this problem.
Vladimir
Fabio, you were right about _Click eventhandler. But it did not solve my problem.
My problem are causing groupboxes on my winform. Why, I don't know.
This is my workaround for CheckStateChanged event that works like charm:
private void My_checkBox_CheckStateChanged(object sender, EventArgs e)
{
if (_addnew == true)
{
CheckBox my_cb = (CheckBox)sender;
if ((my_cb.CheckState == CheckState.Indeterminate) && (my_cb.Text == "Da"))
{
my_cb.Checked = false;
my_cb.Text = "Ne";
}
}
}
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;
In .net 3.5 windows forms I have a listview with "CheckBoxes" = true. Is it possible to dim out or disable some items to prevent the user from checking the box?
You can use the ListBoxItem.ForeColor and UseItemStyleForSubItems properties to make the item look dimmed. Use SystemColors.GrayText to pick the theme color for disabled items. Avoid disabling selection, it prevents the user from using the keyboard. Only disable the checkbox checking. For example:
private void listView1_ItemCheck(object sender, ItemCheckEventArgs e) {
// Disable checking odd-numbered items
if (e.Index % 2 == 1) e.NewValue = e.CurrentValue;
}
You have to roll your own for this. Handle the ListView's ItemSelectionChanged event - if you don't want a particular item to be selectable, do this:
e.Item.Selected = false;
You can make a particular item appear unselectable by graying it out, changing the font color etc.
I took Hans Passant recommendation - good visual approach which in my case denotes un-actionable items.
Here's a sample:
'Select all attachements in case user wants to mask or pick and choose
For i As Integer = 0 To lstView.Items.Count - 1
If Not Scan.SupportedMasking.Contains(Path.GetExtension(lstView.Items(i).Text)) Then
lstView.Items(i).ForeColor = SystemColors.GrayText
lstView.Items(i).Text += " (No masking supported)"
lstView.Items(i).BackColor = SystemColors.InactiveBorder
lstView.Items(i).Selected = False
Else
lstView.Items(i).Selected = True
End If
Next i
use this or set the displaymode to view insted of edit!
public void SetItemEnabled(ListViewItem item, bool enabled)
{
if (item != null)
{
List<ListViewControl> lvControls = this.ListViewControls.FindAll(FindListViewControl(item));
foreach (ListViewControl lvControl in lvControls)
{
if (lvControl.Control != null)
{
lvControl.Control.Enabled = enabled;
}
}
}
}
You should set the AutoCheck property of the checkbox false.
AutoCheck - Gets or set a value indicating whether the Checked or CheckState values and the CheckBox's appearance are automatically changed when the CheckBox is clicked.
Actually this is usable only for the checkbox control.
I'm using a CheckedListBox control in a small application I'm working on. It's a nice control, but one thing bothers me; I can't set a property so that it only checks the item when I actually check the checkbox.
What's the best way to overcome this?
I've been thinking about getting the position of the mouseclick, relative from the left side of the checkbox. Which works partly, but if I would click on an empty space, close enough to the left the current selected item would still be checked. Any ideas regarding this?
I know this thread's a bit old, but I don't think it's a problem to offer another solution:
private void checkedListBox1_MouseClick(object sender, MouseEventArgs e)
{
if ((e.Button == MouseButtons.Left) & (e.X > 13))
{
this.checkedListBox1.SetItemChecked(this.checkedListBox1.SelectedIndex, !this.checkedListBox1.GetItemChecked(this.checkedListBox1.SelectedIndex));
}
}
(With the value of CheckOnClick = True).
You could use that thingy with the rectangle, but why make it more complex the it needs to.
Well, it is quite ugly, but you could calculate mouse hit coordinates against rectangles of items by hooking on CheckedListBox.MouseDown and CheckedListBox.ItemCheck like the following
/// <summary>
/// In order to control itemcheck changes (blinds double clicking, among other things)
/// </summary>
bool AuthorizeCheck { get; set; }
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if(!AuthorizeCheck)
e.NewValue = e.CurrentValue; //check state change was not through authorized actions
}
private void checkedListBox1_MouseDown(object sender, MouseEventArgs e)
{
Point loc = this.checkedListBox1.PointToClient(Cursor.Position);
for (int i = 0; i < this.checkedListBox1.Items.Count; i++)
{
Rectangle rec = this.checkedListBox1.GetItemRectangle(i);
rec.Width = 16; //checkbox itself has a default width of about 16 pixels
if (rec.Contains(loc))
{
AuthorizeCheck = true;
bool newValue = !this.checkedListBox1.GetItemChecked(i);
this.checkedListBox1.SetItemChecked(i, newValue);//check
AuthorizeCheck = false;
return;
}
}
}
Another solution is to simply use a Treeview.
Set CheckBoxes to true, ShowLines to false, and ShowPlusMinus to false and you have basically the same thing as a CheckedListBox. The items are only checked when the actual CheckBox is clicked.
The CheckedListBox is much more simplistic, but the TreeView offers a lot of options that can potentially be better suited for your program.
I succesfully used this property:
CheckedBoxList.CheckOnClick
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.checkedlistbox.checkonclick?view=netframework-4.7.2
The text for a checkbox in a CheckedListBox is rendered by default is to place an HTML label after the checkbox input and set the label's "for" attribute to the ID of the checkbox.
When a label is denoting an element that it is "for," clicking on that label tells the browser to focus on that element, which is what you're seeing.
Two options are to render your own list with separate CheckBox controls and text (not as the Text property of the CheckBox, as that does the same thing as the CheckBoxList) if the list is static or to use something like a Repeater if the list is dynamic.
Try this. Declare iLastIndexClicked as a form-level int variable.
private void chklst_MouseClick(object sender, MouseEventArgs e)
{
Point p = chklst.PointToClient(MousePosition);
int i = chklst.IndexFromPoint(p);
if (p.X > 15) { return; } // Body click.
if (chklst.CheckedIndices.Contains(i)){ return; } // If already has focus click anywhere works right.
if (iLastIndexClicked == i) { return; } // native code will check/uncheck
chklst.SetItemChecked(i, true);
iLastIndexClicked = i;
}
Just checking to see if the user clicked in the leftmost 15 pixels of the checked list (the check box area) works at all times except re-checking a currently selected item. Storing the last index and exiting without changing lets the native code handle that properly, trying to set it to checked in that case turns it on and it just turns back off when the "ItemCheck" code runs.