Checkbox array in C# - c#

Im trying to create a array of Checkboxes in Winforms and I have four Checkboxes and if I click on a Checkbox, a messagebox should display the checkboxes checked.
public void checkboxtest()
{
CheckBox[] boxes = new CheckBox[4];
boxes[0] = checkBox1;
boxes[1] = checkBox2;
boxes[2] = checkBox3;
boxes[3] = checkBox4;
for (int i = 0; i <= 4; i++)
{
if (boxes[i].Checked == true && boxes[i].Enabled)
{
MessageBox.Show("boxes[i] is clicked");
}
}
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
checkboxtest();
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
checkboxtest();
}
continues for 3 and 4 too...
How should I go about it ??
Thanks.

Your loop termination should be i < 4, not i <= 4 since your array only has 4 elements. Also boxes[i].Checked == true is redundant, you can just say boxes[i].Checked.
If you want to display the checked checkboxes when you toggle the state, you'll need to add an event handler to them (to handle the CheckBox.CheckChanged event):
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
_checkBoxes = new CheckBox[] { _checkBox1, _checkBox2, _checkBox3, _checkBox4 };
foreach (var checkBox in _checkBoxes)
checkBox.CheckedChanged += new EventHandler(ShowCheckedCheckboxes);
}
void ShowCheckedCheckboxes(object sender, EventArgs e)
{
string message = string.Empty;
for (int i = 0; i < _checkBoxes.Length; i++)
{
if (_checkBoxes[i].Checked && _checkBoxes[i].Enabled)
{
message += string.Format("boxes[{0}] is clicked\n", i);
}
}
MessageBox.Show(message);
}
CheckBox[] _checkBoxes;
}

Related

C# - ListView : How to handle the mouse click event on a listViewItem?

Let's say I have a ListView on a form and it is populated with records.
How can I do this : when I click (single click) on a row , something has to happen - for example MessageBox.Show("row selected");
How to make this happen? Do I need a mouse click event ? And how can I do this?
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var selectedItemText = (listBox1.SelectedItem ?? "(none)").ToString();
MessageBox.Show("Selected: " + selectedItemText);
}
private void listBox1_MouseClick(object sender, MouseEventArgs e)
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
var rectangle = listBox1.GetItemRectangle(i);
if (rectangle.Contains(e.Location))
{
MessageBox.Show("Item " + i);
return;
}
}
MessageBox.Show("None");
}
#Tommy answer is for ListBox, this one is for ListView :
private void listView1_MouseClick(object sender, MouseEventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
var rectangle = listView1.GetItemRect(i);
if (rectangle.Contains(e.Location))
{
//Write your code here
return;
}
}
}
To prevent unwished behavior on ListView with checkboxes my solution is:
private void lvMembers_MouseClick(object sender, MouseEventArgs e)
{
for (int itemIndex = 0; itemIndex < lvMembers.Items.Count; itemIndex++)
{
ListViewItem item = lvMembers.Items[itemIndex];
Rectangle itemRect = item.GetBounds(ItemBoundsPortion.Label);
if (itemRect.Contains(e.Location))
{
item.Checked = !item.Checked;
break;
}
}
}
If you want to select listview item on mouse click over it try this.
private void timeTable_listView_MouseUp(object sender, MouseEventArgs e)
{
Point mousePos = timeTable_listView.PointToClient(Control.MousePosition);
ListViewHitTestInfo hitTest = timeTable_listView.HitTest(mousePos);
try
{
int columnIndex = hitTest.Item.SubItems.IndexOf(hitTest.SubItem);
edit_textBox.Text = timeTable_listView.SelectedItems[0].SubItems[columnIndex].Text;
}
catch(Exception)
{
}
}

How to unselect last checked item from checkedListBox?

I want to disable multiselection in CheckedListBox. I tried
checkedListBoxWersje.SelectionMode = SelectionMode.One
but I still can check multiple items. So I want to unselect last checked item. Is it possible?
Have you considered using a GroupBox with RadioButtons?
If you really want to go with a CheckedListBox consider the following which allows only one item checked at a time.
namespace CheckListBoxSimple_C_Sharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
}
private const int maxNumberOfCheckedItems = 1;
void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
CheckedListBox items = (CheckedListBox)sender;
if (items.CheckedItems.Count > (maxNumberOfCheckedItems - 1))
{
e.NewValue = CheckState.Unchecked;
}
}
private void Form1_Load(object sender, EventArgs e)
{
checkedListBox1.Items.AddRange(new string[] { "John", "Paul", "George", "Ringo" });
checkedListBox1.SetItemChecked(1, false);
checkedListBox1.SetItemChecked(3, false);
}
}
}
This is the code that works.
if(e.NewValue.Equals(CheckState.Checked))
for (int i = 0; i < checkedListBox1.Items.Count; ++i)
if (i != e.Index)
checkedListBox1.SetItemChecked(i, false);

How To Disable Check/Uncheck Of An Item In A CheckedListBox In C#?

I have a CheckedListBox with 10 items. On each item check a method is being called. I want to disable the checkbox of that particular item for which the method is being executed so that user cannot uncheck the item till the job is completed.
Note: Unchecking of an item calls another method.
Here is the code of ItemCheck Event:
private void host_listbox_ItemCheck(object sender, ItemCheckEventArgs e)
{
int index = e.Index;
try
{
string sitem = host_listbox.Items[index].ToString();
host_list[sitem].checked_event=e;
if (!host_list[sitem].is_busy)
{
host_config.listEnabled = false;
host_list[sitem].con_worker.RunWorkerAsync();
}
if (host_listbox.GetItemCheckState(index) == CheckState.Checked)
{
host_list[sitem].connected = false;
}
}
catch(Exception ex)
{
output_textbox.AppendText("connection failed!" +ex.ToString() +Environment.NewLine);
}
}
You can check/uncheck items in your checkedListBox with this code
checkedListBox.SetItemChecked(item, true);
for more informations go to microsoft documentation
private void host_listbox_ItemCheck(object sender, ItemCheckEventArgs e)
{
int index = e.Index;
try
{
string sitem = host_listbox.Items[index].ToString();
if (host_list[sitem].is_busy // or whatever indicates that background worker is running or any condition that specifies, that you do not want to let this item to be changed)
e.NewValue = e.CurrentValue; //Change the value back
else
{
//Let the checked state of the item change
This code prevent checked state change if associated background work is running:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
workerList = new List<BackgroundWorker>();
for (int i = 0; i < 10; i++)
{
var el = new BackgroundWorker();
el.DoWork += (s, e) =>
{
Thread.Sleep(5000);
};
workerList.Add(el);
checkedListBox1.Items.Add("el " + i);
}
}
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
var worker = workerList[e.Index];
if (worker.IsBusy)
{
e.NewValue = e.CurrentValue;
return;
}
if (e.NewValue == CheckState.Checked)
worker.RunWorkerAsync();
}
public List<BackgroundWorker> workerList { get; set; }
}
Think, that only funcion solution is set selection mode
CheckedListBox.SelectionMode = SelectionMode.None;
private void ItemCheck(object sender, ItemCheckEventArgs e)
{
if (busy)
e.NewValue = e.CurrentValue;
}

2D Array Buttons Display X and Y

I have a small program that hold 4 button in a 2D Array what I want to do is display its 'X' and 'Y' coordinates of the Array in a message box (when clicked)
I have tried a number of ways some don't work and some work but I cant get it to show the 'X' and 'Y' values
The image below shows what I have so far:
And This is the code i have come up with:
namespace _2DArray
{
public partial class Form1 : Form
{
private Button[,] b;
public Form1()
{
InitializeComponent();
b = new Button[2, 2];
b = new Button[,] { {button1,button2 },
{button3, button4}};
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (Button bt in b)
{
bt.Click += new System.EventHandler(this.ClickedButton);
}
}
private void ClickedButton(object sender, EventArgs e)
{
Button s = (Button)sender;
MessageBox.Show("you have clicked button:" + s);
}
}
}
Here is the answer to your question if i read it right. You are trying to get the X and Y coordinates of the button right?
Here is the code for a button click:
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(button1.Location.ToString());
}
try assigning some sort of pointer like give name of the button to keep track of it coordinates
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
b[i, j].Click += new System.EventHandler(this.ClickedButton);
b[i, j].Name =i+" "+j;
}
}
}
private void ClickedButton(object sender, EventArgs e)
{
Button s = (Button)sender;
MessageBox.Show("you have clicked button:" + s.Name);
}
Use this code
private void Form1_Load(object sender, EventArgs e) {
for (int x = 0; x < 2; x++) {
for (int y = 0; x < 2; y++) {
b[x, y].Tag = new Point(x, y);
b[x, y].Click += new System.EventHandler(this.ClickedButton);
}
}
}
private void ClickedButton(object sender, EventArgs e) {
Button s = (Button) sender;
MessageBox.Show("you have clicked button:" + s.Tag.ToString());
}
then clicking on button1 will show the message "you have clicked button:{X = 0, Y = 0}" etc
Tag is a property that each control has, it's description is "User-defined data associated with the object" so you can set it to whatever object you like.
I know this is probably a bit late for the op but hopefully it will help someone else.

How do I combine these three sets of code

I have three radio buttons. The code behind their change events is as follows:
private void uxRajRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (uxRajRadioButton.Checked == true)
{
uxPersonBettingLabel.Text = "Raj";
GuySelected = 0;
uxBetNumericUpDown.Maximum = Guys[GuySelected].Cash;
}
}
private void uxPaulRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (uxPaulRadioButton.Checked == true)
{
uxPersonBettingLabel.Text = "Paul";
GuySelected = 1;
uxBetNumericUpDown.Maximum = Guys[GuySelected].Cash;
}
}
private void uxMikeRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (uxMikeRadioButton.Checked == true)
{
uxPersonBettingLabel.Text = "Mike";
GuySelected = 2;
uxBetNumericUpDown.Maximum = Guys[GuySelected].Cash;
}
}
With just three radio buttons this is acceptable but if I had say 7 radio buttons each with 20 lines of code behind its change event then it would be a lot of (needless?) code. I've attempted to shorten the above and ended up with the following. Is this correct?
private void uxRajRadioButton_CheckedChanged(object sender, EventArgs e)
{
radioButtonCode(this.uxRajRadioButton, 0);
}
private void uxPaulRadioButton_CheckedChanged(object sender, EventArgs e)
{
radioButtonCode(this.uxPaulRadioButton,1);
}
private void uxMikeRadioButton_CheckedChanged(object sender, EventArgs e)
{
radioButtonCode(this.uxMikeRadioButton, 2);
}
int GuySelected=0;
public void radioButtonCode(RadioButton myRadio, int mybettorIndex)
{
if (myRadio.Checked == true)
{
GuySelected = mybettorIndex;
uxPersonBettingLabel.Text = Guys[GuySelected].Name;
uxBetNumericUpDown.Maximum = Guys[GuySelected].Cash;
}
}
Could you have the same event handler for all the radio buttons? Something like
private void uxRadioButton_CheckedChanged(object sender, EventArgs e)
{
radioButtonCode((RadioButton)sender);
}
public void radioButtonCode(RadioButton myRadio)
{
if (myRadio.Checked == true)
{
int guySelected = getGuySelectedIndex(myRadio);
uxPersonBettingLabel.Text = Guys[guySelected].Name;
uxBetNumericUpDown.Maximum = Guys[guySelected].Cash;
}
}
public int getGuySelectedIndex(RadioButton myRadio)
{
int index = 0;
if (myRadio == this.uxRajRadioButton) index = 0;
else if (myRadio == this.uxPaulRadioButton) index = 1;
else if (myRadio == this.uxMikeRadioButton) index = 2;
return index;
}
Your second code sample, where you have extracted the commonalities out to a function looks like the way I would have done this refactoring.
It is about as good as you can make it, barring the name (UpdateUserInfo might be slightly better).
There is a better way. Declare an array of radio buttons and bind them to above event at run time. This binding code won't be inside designer page. This will result in single ArrayRadio_checkedChange event. In this method you can use sender property to figure out the proper radio button's index and take action accordingly.
you can use
uxRajRadioButton.CheckedChanged += new EventHandler(rb_CheckedChanged);
uxPaulRadioButton.CheckedChanged += new EventHandler(rb_CheckedChanged);
...
uxRajRadioButton.Tag =new KeyValuePair<string,int>("Raj",0);
uxPaulRadioButton.Tag =new KeyValuePair<string,int>("Paul",1);
....
private void rb_CheckedChanged(object sender, EventArgs e)
{
if(!(sender is RadioButton))
return;
RadioButton myRadio= sender as RadioButton;
if (myRadio.Checked == true)
{
myRadio.Text = (myRadio.Tag as KeyValuePair<string,int>).Key;
GuySelected = (myRadio.Tag as KeyValuePair<string,int>).Value;
uxBetNumericUpDown.Maximum = Guys[GuySelected].Cash;
}
}
What I usually do is I put the index in the tag attribute. This way you can bind this event to every RadioButton
public void uxRadioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton myRadio = (RadioButton) sender;
if (myRadio.Checked)
{
GuySelected = (int)myRadio.Tag;
uxPersonBettingLabel.Text = Guys[GuySelected].Name;
uxBetNumericUpDown.Maximum = Guys[GuySelected].Cash;
}
}

Categories

Resources