Disabling a checkbox when another checkbox is clicked - c#

I am trying to disable the thin and crispy checkbox when traditional checkbox is clicked. I have these in a group due to me enabling the whole group when the numericUpDown value is set to 1. When I click traditional checkbox, it doesn't disable the thin and crispy checkbox. I am using windows form application
Code
private void NudQuantity1_ValueChanged(object sender, EventArgs e)
{
if (NudQuantity1.Value == 0)
{
gbCheesePizza.Enabled = false;
}
else
{
gbCheesePizza.Enabled = true;
}
if (CBXTraditional1.Checked == true)
{
CBXthinandcrispy1.Enabled = false;
}
}
When I run this code outside of a groupbox, it works perfectly.

I don't think this block should be inside the event handler
if (CBXTraditional1.Checked == true)
{
CBXthinandcrispy1.Enabled = false;
}
It means that, provided you've got no other event handling for the checkboxes, this code will only be executed when you change the value of NudQuantity1 so it won't execute anything when you click the checkboxes afterwards.
Try use radio buttons as Steve mentioned. They do this for you.

Related

How to make correct initialization of ComboBox?

I need show droppeddown combobox after start program.
I need in dropdown style only, not simple style.
This is simple fragment of my program:
private void Form1_Shown(object sender, EventArgs e)
{
CB1.Items.Add("1");
CB1.DropDownStyle = ComboBoxStyle.DropDown;
CB1.DroppedDown = true;
}
But I found the watch sign as cursor till I click on Form in any place.
I guessed that my Form have not fully active state and wait for something.
When I click Form (or combobox or any control) by LBM, it activated fully and all works fine.
Of course the combobox is dropup then, so I need click combobox twice.
Еell me please what is correct initialization of such style combobox without "Cursor = Cursors.Default;"
You can simply wait until cursor is the default:
while (Cursor.Current != Cursors.Default)
{
Application.DoEvents();
}
CB1.Items.Add("1");
CB1.DropDownStyle = ComboBoxStyle.DropDown;
CB1.DroppedDown = true;
Application.DoEvents simply process messages from the window queue, so you can process message until you get that cursor is the default. In that moment, you can drop down your control without problem.
If you prefer, create a extension method for the Form:
public static class FormExtends
{
public static void WaitToDefaultCursor(this Form form)
{
while (Cursor.Current != Cursors.Default)
{
Application.DoEvents();
}
}
}
And use it:
this.WaitToDefaultCursor();
CB1.Items.Add("1");
CB1.DropDownStyle = ComboBoxStyle.DropDown;
CB1.DroppedDown = true;
NOTE: I use Cursor.Default but not to change the cursor. The form is processing messages and it's difficult to select a good moment to drop down the control.

How to change default radio button checked in c#

How to check radio button default
For example, if I have 5 radio buttons in the group, I want to check the default 1st radio button.
I need a code for updating it, like when the project is running, and I click the 2nd radio button, and the update button default should change to the 2nd radio button.
Select all RadioButtons with Strg
Go to Events and double click CheckedChanged
Then just check whether the button is checked or not
private void radioButton3_CheckedChanged_1(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
//Do something
}
else if (radioButton2.Checked)
{
//Do something
}
else if (radioButton3.Checked)
{
//Do something
}
}
If you are using Winforms
Add Settings to you project (Set int value)
Add the Code will save the current radio checked Add in all radios
Properties.Settings.Default.currentRadio = 1;
Properties.Settings.Default.Save();
In the form initializing set the current checked Radio
if (Properties.Settings.Default.currentRadio == 1)
{
radioButton1.Checked = true;
}
else if(Properties.Settings.Default.currentRadio == 2)
{
radioButton2.Checked = true;
}

Setting myButton.Enabled = true causes radiobutton's CheckedChanged handler to fire

I have absolutely no programmatic links or properties set such that my CheckedChanged fires as a result of anything except checking the radio button.
However, when I click a different, unrelated button, the button's click handler fires (this is expected). In this click handler, the button disables itself (it re-enables on a different button's click), which then triggers myRadioButton_CheckedChanged handle for an unrelated radiobutton fires.
The call stack that I'm seeing is essentially
myRadioButton_CheckedChanged (...)
myButton_Click(...)
Main(...)
The line in myButton_Click that is triggering the myRadioButton_CheckedChanged is apparently
myButton.Enabled = false;
The related code is:
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
// L-R
if (radioButton1.Checked == true)
{
orientation_left = 3;
pictureBox2.Invalidate();
Debug.Print("left {0}", orientation_left);
}
}
private void select1_Click(object sender, EventArgs e)
{
Debug.Print("select1click");
if (select1Down == false)
{
// ... stuff
select1.Enabled = false; // Causing the CheckedChanged to fire
select2.Enabled = false;
select1Down = true;
}
}
Ok, got it.
Check the TabOrder on your Button and RadioButton.
Seems that when you disable the Button, the focus is shifted to the next control, which is probably your RadioButton, causing it to become checked.
On my test From, all I had to do was to make sure that the RadioButton's TabOrder was not right after the Button.
Cheers
EDIT:
This seems to be a known problem as I just found this MSDN thread: http://social.msdn.microsoft.com/Forums/windows/en-US/77fbec3b-1f63-42e1-a200-19b261b63794/the-radiobutton-clicked-event-is-fired-without-the-radio-button-beeing-clicked-?forum=winforms
Okay, it's kinda hacky but it works without changing anything to the tab order:
private void select1_Click(object sender, EventArgs e)
{
if (!select1Down)
{
// ... stuff
SendKeys.SendWait("{Tab}");
select1.Enabled = false;
select2.Enabled = false;
select1Down = true;
}
}

ListView Checkbox Behavior

I have a Winform application I'm modifying for a friend. It has a listview and wants me to add a checkbox to each row and make them mutually exclusive. So in my testing of how to make it work I found a strange behavior and as hopping someone could tell me what I'm missing.
If I display the List view with no checkbox checked. When I click right on the checkbox I cannot get it to check, but the row dose get selected. If I click on the item (the name in this case) in the column it does get checked and selected.
No matter where I click on a row, any checkboxes in rows not selected will be uncheck. Here is my little test program. I’m using .NET 4
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
TestListView.Items.Add("Bob");
TestListView.Items.Add("Ann");
TestListView.Items.Add("Frank");
}
void TestListView_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e) {
ListViewItem currentItem = TestListView.GetItemAt(e.X, e.Y);
if (currentItem != null) {
foreach (ListViewItem item in TestListView.Items) {
if (item.Text == currentItem.Text) {
item.Checked = true;
item.Selected = !currentItem.Selected;
}
else
item.Checked = false;
}
}
}
}
Seems that WinForms is checking the checkbox when you click on the checkbox directly, and then your code immediately undoes the checking, so you never see it.
Perhaps instead of MouseClick you should use the ItemCheck or ItemChecked event. The first is fired before the Checked property changes, the second after.
I'm currently having a very similar issue as well, however in response to Timwi it's not the code doing the unchecking. I've been stepping through it very slowly and as the code fires when clicking on a checkbox, it states that it has checked it. But when the form resumes, it is unchecked again. After reading Timwi post, he lead me onto the answer. It's not the code doing the unchecked, but the winforms event firing afterwards that unchecks the box. This fixes it:
My code is:
private bool allowCheck = false;
private bool preventOverflow = true;
private void lstvwRaiseLimitStore_MouseClick(object sender, MouseEventArgs e)
{
preventOverflow = false;
ListViewItem item = lstvwRaiseLimitStore.HitTest(e.X, e.Y).Item;
if (item.Checked)
{
allowCheck = true;
item.Checked = false;
}
else
{
allowCheck = true;
item.Checked = true;
}
}
private void lstvwRaiseLimitStore_ItemChecked(object sender, ItemCheckedEventArgs e)
{
if (!preventOverflow)
{
if (!allowCheck)
{
preventOverflow = true;
e.Item.Checked = !e.Item.Checked;
}
else
allowCheck = false;
}
}
So what it is doing, first I have to set a flag to prevent overflow, otherwise when the form is built or when you uncheck windows checking the box, it keeps looping the code and will eventually stack overflow. Next flag is the actual allow checking of the checkbox via your code and not via another method.
Clicking on them item, it locates where the click was and then sets the flag to allow a check to be done. The code then checks the box and the item checked section kicks off, becuase it was done by our code, it does nothing but reset the allowcheck flag.
If you clicked on a line, it does nothing else, however if it was a checkbox, at the end of our code, the Windows function kicks off and tries to check the box, becuase the allowcheck flag is false, the code first sets a flag to say I'm already preventing a check and then resets the check back to it's intial status. Becuase this is done, the itemchecked event kicks off again, but the code has set the flag to prevent it from doing anything. Then the code finishes and it has prevented windows from checking the check box and only allowed our code.
Hope it helps!

Select Tab Page in TabControl without stealing focus

Using TabControl.SelectTab("...") shows the tab but it also gives the tab focus. I would like to show a particular tab, but keep focus where it is.
I have data rows in a grid. Based on properties of the selected row, I show a different tab page to have a different UI layout. But when using arrow keys to scroll through rows, the focus switches to the selected tab -- which I don't want to happen.
Thanks.
You can try disabling the TabControl before setting the selected tab, then re-enabling it. This will prevent it from taking focus. I tested this on a tab control with a few controls on it, and didn't see any visual change, but you'll have to try it in your UI and see whether it's ok for you.
tabControl1.Enabled = false;
tabControl1.SelectTab("tabPage4");
tabControl1.Enabled = true;
To be safe, you could put the line to re-enable the TabControl in a finally block to make sure it doesn't get left disabled.
I don't think there's a built-in function, but you can do in this way:
private bool skipSelectionChanged = false;
private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
if (skipSelectionChanged)
return;
// supposing we decide tab[0] has to be selected...
this.SelectTabWithoutFocus(this.tabControl1.TabPages[0]);
}
private void SelectTabWithoutFocus(TabPage tabPage)
{
this.skipSelectionChanged = true;
// "this" is the form in my case, so you get the current focused control
// (ActiveControl), backup it, and re-set it after Tab activation
var prevFocusedControl = this.ActiveControl;
if (this.ActiveControl != null)
{
this.tabControl1.SelectedTab = tabPage;
prevFocusedControl.Focus();
}
this.skipSelectionChanged = false;
}
Here, I backup the current focused control, select the desired tab, and finally set the focus to the original control.
Skipping boolean is necessary, because giving the focus to the grid you trigger SelectionChanged event again, causing infinite looping.
This selects the tab pages while keeping the focus on top, as asked here above:
tc.TabPages[0].Enabled = false;
tc.SelectTab(0);
tc.TabPages[0].Enabled = true;
tc is here my instance for the TabControl type (i. e. it IS my tab control, and it has a few "tab pages"). This works properly for me. My purpose is to loop through these tab pages with the Left and Right keys (arrows) i. e. when I go forwards (by Key.Right) and reach the last tabpage I want to have my focus on [0] without activating the DataGridView which I have in that page, and when I go backwards (by Key.Left) and reach [0] I want to have [tc.TabCount - 1] enabled, which is the last one. The code for this case is:
tc.TabPages[tc.TabCount - 1].Enabled = false;
tc.SelectTab(tc.TabCount - 1);
tc.TabPages[tc.TabCount - 1].Enabled = true;
The complete piece of code is:
private bool KeyTc(System.Windows.Forms.Keys keyData)
{
if (keyData == K.Left && tc.SelectedIndex == 0)
{
tc.TabPages[tc.TabCount - 1].Enabled = false;
tc.SelectTab(tc.TabCount - 1);
tc.TabPages[tc.TabCount - 1].Enabled = true;
return true;
}
else if (keyData == K.Right && tc.SelectedIndex == tc.TabCount - 1)
{
tc.TabPages[0].Enabled = false;
tc.SelectTab(0);
tc.TabPages[0].Enabled = true;
return true;
}
return false;
}
This bool KeyTc is returned to a case in a switch statement for key evaluation in:
protected override bool ProcessCmdKey(ref Message keyMsg, Keys keyData)
{ switch keyData { ... } }
Base on the solution proposed by "Jeff Ogata : You can try disabling the TabControl before setting the selected tab, then re-enabling it. This will prevent it from taking focus", here bellow my solution:
tabMain.SelectedPageChanging += (s, e) =>
{
tabMain.Enabled = false;
};
tabMain.SelectedPageChanged += (s, e) =>
{
tabMain.Enabled = true;
};
Note: this code is using DevExpress "DevExpress.XtraTab.XtraTabControl".

Categories