Swap two check boxes values - checkbox

I have 2 check boxes. I want to uncheck when I check the other and vice-versa. So , always, I'll have only one checked and the other unchecked. What I'm having now is when I check one, the other is unchecked (good). Now, when I go to the unchecked and check it, both become unchecked in the first click. Here is my example:
def CB1Function():
CB2.setChecked(0)
CB1.stateChanged.connect(CB1Function)
def CB2Function():
CB1.setChecked(0)
CB2.stateChanged.connect(CB2Function)
In other words, for example, I have 3 options with 3 checkboxes, I'm supposed to select only one option at a time.
Thanks

It might be a silly answer but why not use radiobuttons?
A radio button or option button is a type of graphical user interface element that allows the user to choose only one of a predefined set of options.
Source: http://en.wikipedia.org/wiki/Radio_button

Sounds like a radiobutton indeed. But if you insist on checkboxes, try something like this:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
checkBox2.Checked = !checkBox1.Checked;
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
checkBox1.Checked = !checkBox2.Checked;
}
EDIT: if you have more then two checkboxes (and even with two) you could make a procedure that loops through all checkboxes and changes them, something like (pseudocode):
private void CheckAllCheckboxes(checkbox ACheckbox) //ACheckbox is the checkbox just clicked
{
bool JustChecked = ACheckbox.checked; //did you enable or disable ACheckbox?
for (int i = 0; i <= AllCheckBoxes.count; i++)
{
if (AllCheckboxes[i] != ACheckbox) //every checkbox except the one just checked...
{
AllCheckBoxes[i].checked = !JustChecked //set the opposite
}
}
}

Related

If else condition on radio buttons

I was able to create buttons.I will be using about 65 buttons, how do you use if else condition on the buttons? Can someone please show me an example? Thank you in advance.
private void createButtons()
{
flowLayoutPanel1.Controls.Clear();
for(int i = 0;i <10;i++)
{
RadioButton b = new RadioButton();
b.Name = i.ToString();
b.Text = "radiobutton" + i.ToString();
b.AutoSize = true;
flowLayoutPanel1.Controls.Add(b);
}
}
How about putting the RadioButtons in a list or an array? This way you could use if (allRadioButtons[1].checked) {...}.
Here is an example
private List<RadioButton> allRadioButtons = new List<RadioButton>();
private void createButtons()
{
flowLayoutPanel1.Controls.Clear();
for (int i = 0; i < 10; i++)
{
RadioButton b = new RadioButton();
b.Name = i.ToString();
b.Text = "radiobutton" + i.ToString();
b.AutoSize = true;
flowLayoutPanel1.Controls.Add(b);
//add every button to the list
//the one with the Text radiobutton0 will be accessible as allRadioButtons[0]
//the one with the Text radiobutton1: allRadioButtons[1]
//etc
allRadioButtons.Add(b);
}
}
//you can use your list in any other method
private void myMethod() {
if (allRadioButtons[0].Checked)
{
//do something
}
}
If Andrea's answer didn't work for you (since you didn't mark it as a solution), another option would be to create a container, such as a GroupBox, and then add your programatically created RadioButton controls to this container. Then you can loop over the controls belonging to the GroupBox like this:
foreach (Control c in myGroupBox.Controls)
{
if ((RadioButton)c).Checked)
//Do something
}
This will loop over all the controls in the GroupBox and cast them to a RadioButton and check if they're checked or not. I've used something similar to this as the basis for quite a few requirements in different applications; it's very easy to make a recursive method that takes a ControlCollection, loop over it and apply logic as needed depending on some condition, like the type of control or perhaps the Tag value of the control.
Then as far as adding the RadioButtons to the GroupBox at run time you just do something like myGroupBox.Controls.Add(b) where b is the RadioButton you've created in your for loop in your sample code. More on runtime control creation here.

Interact with the Ok/Accept Or Cancel Button of a RepositoryItemTimeSpanEdit?

as seen in this post, I need to interact with the button, I mean, save the value of the repository when the user press the OK button, any suggest?
You need to find your TimeSpanEdit control inside of the popup form. You can iterate through popupForm.Controls collection to find out the control with TimeSpanEdit type. Here is example of how to do it. After that you can use TimeSpanEdit.TimeSpan property to get the value of TimeSpanEdit control.
private void OkButton_Click(object sender, EventArgs e)
{
var popupForm = (TimeSpanEditDropDownForm)OwnedForms.FirstOrDefault(item => item is TimeSpanEditDropDownForm);
if (popupForm == null)
return;
var timeSpanEdit = GetAll(this, typeof(TimeSpanEdit)).FirstOrDefault();
if (timeSpanEdit == null)
return;
MessageBox.Show(timeSpanEdit.TimeSpan.ToString());
}
public IEnumerable<Control> GetAll(Control control,Type type)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetAll(ctrl,type))
.Concat(controls)
.Where(c => c.GetType() == type);
}
I think you can use object sender. sender will contains probably TimeSpanEditDropDownForm and there you should get actual value of this form. :)
I presume this code is called from controller is it?
if it is true than you have View.CurrentObject and you must know which property uses this TimeSpanEditDropDownForm so you could do something like this.
private void OkButton_Click(object sender, EventArgs e)
{
MyClass myClass = View.CUrrentObject as MyClass;
TimeSpanEditDropDownForm timeSpanForm = sender as TimeSpanEditDropDownForm;
myClass.CurrentTime = timeSpanForm.CurrentTime;
myClass.Session.CommitChanges();
MessageBox.Show("Ok");
}
I dont know what is name of right attribute wich store TimeSpan inside TimeSpanEditDropDownForm thats thing you must find out but I think it could helps :)

programatically add button click in winforms?

is it possible to add button click event? i want to add controls dynamicly but i don't bind event's to my controls.
this.buttonDeneme = new System.Windows.Forms.Button();
this.buttonDeneme.Location = new System.Drawing.Point(150, 90);
this.buttonDeneme.Name = "button1";
this.buttonDeneme.Size = new System.Drawing.Size(122, 23);
this.buttonDeneme.TabIndex = 0;
this.buttonDeneme.Text = "FileUpload";
this.buttonDeneme.UseVisualStyleBackColor = true;
this.buttonDeneme.Click += ????
#dotTutorial answer is going to work but lot's people still have difficulty with Linq and Lambda expression so if you don't understand it the very basic way to write this is :
this.buttonDeneme.Click += new EventHandler(MyCustomClickHandler);
void MyCustomClickHandler(object sender, EventArgs e)
{
// do whatever you want here
}
but creating multiple button is usually because they wont do the same exact thing so you might want to set the this.buttonDeneme.Tag to some sort of identifier. i prefer using string in there.
then in the click event you can retrieve that value and know what to do. here a corrected version with the Tag used :
this.buttonDeneme.Tag = "SearchBook";
this.buttonDeneme.Click += new EventHandler(MyCustomClickHandler);
void MyCustomClickHandler(object sender, EventArgs e)
{
// for button created above the value when
// the click is called will be "SearchBook"
string sTag = ((Button)sender).Tag.ToString();
if(sTag == "SearchBook")
{
// do stuff for search book
}
else if(sTag == "blablabla")
{
// do other stuff
}
}
The easiest alternative would be to use a lambda expression.
this.buttonDeneme.Click += ((s, e) => {
// The code that handles a click event
});
's' will be the sender object and 'e' the eventargs.

textbox validated method does not work while assigning value to textbox

I am using c#.net 2.0 winforms. I use errorprovider control in my form to validate a textbox. While I programatically assign value to that textbox. textbox validated method does not take the value from the textbox or considers it a blank value. How can I validate my textbox by without entering value in the textbox. Here is the code
private void textBox6_Validated(object sender, EventArgs e)
{
bTest6 = txtRegExPinIsValid(textBox6.Text);
if (bTest6)
{
this.errorProvider1.SetError(textBox6, "");
}
else
{
this.errorProvider1.SetError(textBox6, "This field must contain Exactly 6 digits");
}
}
private bool txtRegExPinIsValid(string textToValidate)
{
Regex TheRegExpression;
string TheTextToValidate;
string TheRegExTest = #"^\d{6}$";
TheTextToValidate = textToValidate;
TheRegExpression = new Regex(TheRegExTest);
// test text with expression
if (TheRegExpression.IsMatch(TheTextToValidate))
{
return true;
}
else
{
return false;
}
}
While performing update operation I fill the textbox with values from the ms access table. If the value is correct, just leave it otherwise I have to update it. Please help me. Thanks in advance
I would recommend placing the validation code in a separate method. Call that method from both the Validated event and the location in your code where you need to programatically validate, as shown below:
// Call this from wherever you need to validate a TextBox
void PerformValidation(TextBox textBox)
{
bTest6 = txtRegExPinIsValid(textBox6.Text);
if (bTest6)
{
this.errorProvider1.SetError(textBox6, "");
}
else
{
this.errorProvider1.SetError(textBox6, "This field must contain Exactly 6 digits");
}
}
private void textBox6_Validated(object sender, EventArgs e)
{
PerformValidation(textBox6);
}

WinForms ListBox with readonly/disabled items

Is there a way to make some of the items in a ListBox readonly/disabled so they can't be selected? Or are there any similar controls to ListBox to provide this functionality?
ListBox doesn't have support for that. You can bolt something on, you could deselect a selected item. Here's a silly example that prevents even-numbered items from being selected:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
for (int ix = listBox1.SelectedIndices.Count - 1; ix >= 0; ix--) {
if (listBox1.SelectedIndices[ix] % 2 != 0)
listBox1.SelectedIndices.Remove(listBox1.SelectedIndices[ix]);
}
}
But the flicker is quite noticeable and it messes up keyboard navigation. You can get better results by using CheckedListBox, you can prevent the user from checking the box for an item:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
if (e.Index % 2 != 0) e.NewValue = CheckState.Unchecked;
}
But now you cannot override drawing to make it look obvious to the user that the item isn't selectable. No great solutions here, it is far simpler to just not display items in the box that shouldn't be selectable.
#Hans solution causing that the item id selected for a short time and then selection disappearing. I don't like that - this can be confusing for the enduser.
I prefer to hide some edit option buttons for the item that should be disabled:
if (lbSystemUsers.Items.Count > 0 && lbSystemUsers.SelectedIndices.Count > 0)
if (((RemoteSystemUserListEntity)lbSystemUsers.SelectedItem).Value == appLogin)
{
bSystemUsersDelete.Visible = false;
bSystemUsersEdit.Visible = false;
}
else
{
bSystemUsersDelete.Visible = true;
bSystemUsersEdit.Visible = true;
}
Here is the list that lists the users and disallow to edit user that is actually logged in to the edit panel.
ListBox doesn't have a ReadOnly (or similar) property, but you can make a custom ListBox control. Here's a solution that worked pretty well for me:
https://ajeethtechnotes.blogspot.com/2009/02/readonly-listbox.html
public class ReadOnlyListBox : ListBox
{
private bool _readOnly = false;
public bool ReadOnly
{
get { return _readOnly; }
set { _readOnly = value; }
}
protected override void DefWndProc(ref Message m)
{
// If ReadOnly is set to true, then block any messages
// to the selection area from the mouse or keyboard.
// Let all other messages pass through to the
// Windows default implementation of DefWndProc.
if (!_readOnly || ((m.Msg <= 0x0200 || m.Msg >= 0x020E)
&& (m.Msg <= 0x0100 || m.Msg >= 0x0109)
&& m.Msg != 0x2111
&& m.Msg != 0x87))
{
base.DefWndProc(ref m);
}
}
}
I know this is old thread, but i'll post a workaround for other readers in future.
listBox.Enabled = false;
listBox.BackColor = Color.LightGray;
This will change background color of list box to Light Gray. So this is not builtin "native way" to do it, but at least gives user some feedback that he is not supposed to / can't edit that field.
To get read-only behaviour I have MyCBLLocked, a boolean associated with the MyCBL checkbox list control, and on the CheckItem event I do:
private void MyCBL_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (MyCBLLocked)
e.NewValue = e.CurrentValue;
}
So instead of
MyCBL.Enabled = false;
I use
MyCBLLocked = true;
and the user can scroll through the many selections but not mess things up with changes.

Resources