This question already has answers here:
Only one checkbox to be selected
(6 answers)
Closed 6 years ago.
I am struggling with why my code is not working. This is for a school assignment. I am allowed to ask for help. I am new to programming. I am using visual studio 2015. I am trying to get it so the user must only be allowed to select one checkbox. I have other checkboxes in this assignment so using last checked will not work. I am not getting errors, it just does nothing. Thanks!
My checkBoxes are named checkBox1, checkBox2,......5
My entire current code is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Chapter6Homework
{
public partial class IceCreamOrder : Form
{
public IceCreamOrder()
{
InitializeComponent();
}
private void btn_Clear_Click(object sender, EventArgs e)
{
// Clear flavors by automatically selecting default button on Clear button click
rdbDefault.Checked = true;
// Clear toppings
checkBox_CookieDough.CheckState = CheckState.Unchecked;
checkBox_ChocolateSyrup.CheckState = CheckState.Unchecked;
checkBox_Marshmallows.CheckState = CheckState.Unchecked;
checkBox_OreoPieces.CheckState = CheckState.Unchecked;
checkbox_Sprinkles.CheckState = CheckState.Unchecked;
checkbox_Walnuts.CheckState = CheckState.Unchecked;
// Clear List Box
lstDisplay.Items.Clear();
// Clear scoops
checkBox1.CheckState = CheckState.Unchecked;
checkBox2.CheckState = CheckState.Unchecked;
checkBox3.CheckState = CheckState.Unchecked;
checkBox4.CheckState = CheckState.Unchecked;
checkBox5.CheckState = CheckState.Unchecked;
}
private void btn_CalculateCost_Click(object sender, EventArgs e)
{
// Verify user selected a flavor
if (rdbDefault.Checked == true)
{
MessageBox.Show("Please select a flavor");
return;
}
// Verify user seleted # of scoops
if (checkBox1.CheckState == CheckState.Unchecked &&
checkBox2.CheckState == CheckState.Unchecked &&
checkBox3.CheckState == CheckState.Unchecked &&
checkBox4.CheckState == CheckState.Unchecked &&
checkBox5.CheckState == CheckState.Unchecked)
{
MessageBox.Show("You must select a number of scoops. 1 is a must but 5 is recommended!");
return;
}
//Verify user got the toppings they wanted if any
if (checkBox_ChocolateSyrup.CheckState == CheckState.Unchecked &&
checkBox_CookieDough.CheckState == CheckState.Unchecked &&
checkBox_Marshmallows.CheckState == CheckState.Unchecked &&
checkBox_OreoPieces.CheckState == CheckState.Unchecked &&
checkbox_Sprinkles.CheckState == CheckState.Unchecked &&
checkbox_Walnuts.CheckState == CheckState.Unchecked)
{
DialogResult dr = MessageBox.Show("Are you sure you don't want toppings?",
"help", MessageBoxButtons.YesNo);
switch (dr)
{
case DialogResult.Yes: break;
case DialogResult.No: return;
}
}
// Declare Variables and constants
double flavorCost = FlavorCost();
double toppingCost = ToppingCost();
double scoops = Scoops() * flavorCost;
double subTotal = (flavorCost + toppingCost + scoops);
double salesTax = subTotal * .08;
double total = subTotal + salesTax;
// Display total price of order
lstDisplay.Items.Clear();
lstDisplay.Items.Add("Total: " + total.ToString("C2"));
// Display total sales tax
lstDisplay.Items.Add("");
lstDisplay.Items.Add("Sales Tax: " + salesTax.ToString("C2"));
// Display Flavor Cost
lstDisplay.Items.Add("Flavor: " + flavorCost.ToString("C2"));
// Display Scoops Cost
lstDisplay.Items.Add("Scoops: " + scoops.ToString("C2"));
// Display Toppings
lstDisplay.Items.Add("Toppings: " + toppingCost.ToString("C2"));
}
// Get flavor cost
Double FlavorCost()
{
if ((radioButton_Chocolate.Checked == true) || (radioButton_Strawberry.Checked == true))
return 1.5F;
else if (radioButton_Vanilla.Checked == true)
return 1.25F;
else
return 0;
}
// Get num of scoops
Double Scoops()
{
if (checkBox1.Checked == true)
return 1;
else if (checkBox2.Checked == true)
return 2;
else if (checkBox3.Checked == true)
return 3;
else if (checkBox4.Checked == true)
return 4;
else if (checkBox5.Checked == true)
return 5;
else
return 0;
}
// Get Toppings
Double ToppingCost()
{
if ((checkBox_ChocolateSyrup.Checked == true) ||
(checkBox_Marshmallows.Checked == true) ||
(checkbox_Sprinkles.Checked == true))
return .25F;
else if ((checkBox_OreoPieces.Checked == true) ||
(checkBox_CookieDough.Checked == true) ||
(checkbox_Walnuts.Checked == true))
return .50F;
else
return 0;
}
private void IceCreamOrder_Load_1(object sender, EventArgs e)
{
//Set Default to true on load
rdbDefault.Checked = true;
}
internal class Sub
{
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
int numberChecked = 0;
CheckBox[] array = new
CheckBox[] { checkBox1, checkBox2, checkBox3, checkBox4, checkBox5 };
for (int i = 0; i < array.Length; i++)
{
if
(array[i].Checked)
numberChecked++;
else if
(numberChecked > 1)
MessageBox.Show("You have checked "
+ numberChecked.ToString() + " checkBoxes. Only one is allowed.");
else
return;
}
}
}
}
Use RadioButton with grouping.
To make your solution work: ( sender is the selected checkbox )
private void checkBox1_Checked(object sender, EventArgs e)
{
var array = new CheckBox[] { checkBox1, checkBox2, checkBox3, checkBox4, checkBox5 };
foreach(var checkbox in array)
{
if(checkbox != sender){
checkbox.IsChecked = false
}
}
Related
I'm creating a datagridview in WinForms. Each cell in the datagridview is either a textboxcell or datagridview image cell. I'm firing a cellMouseDownEent( object sender, DataGridViewCellMouseEventArgs e). If the sected cell is a image cell I perform task1 and if it is textboxcell I perform task2. I'm not getting how to find out whether the current cell is image cell or text box cell. I tried setting tag property of image cell to 0 and textboxcell cell to 1 to identify which is being clicked, but no luck. Any advice is aapreciated.
Thanks,
I'm adding my code here:
Ignore if a column or row header is clicked
if (e.RowIndex != -1 && e.ColumnIndex != -1)
{
if (e.Button == MouseButtons.Right)
{
DataGridViewCell clickedCell = (sender as DataGridView).Rows[e.RowIndex].Cells[e.ColumnIndex];
// Here you can do whatever you want with the cell
this.dgvAddFilters.CurrentCell = clickedCell; // Select the clicked cell, for instance
// Get mouse position relative to the vehicles grid
var relativeMousePosition = dgvAddFilters.PointToClient(Cursor.Position);
if (clickedCell.Tag.ToString()==null)
{
return;
}
else if (imageCell == null) return;
else if (e.ColumnIndex == 0 && e.RowIndex == 0)
{
if ((dgvAddFilters[e.ColumnIndex, e.RowIndex + 2].Value == null))
// (dgvAddFilters[e.ColumnIndex + 2, e.RowIndex].Value == null))
{
dgvAddFilters.ContextMenuStrip = contMenuOr;
this.contMenuOr.Show(dgvAddFilters, relativeMousePosition);
}
else return;
}
else if ((e.ColumnIndex == 0)
&& (e.RowIndex > 0)
&& (dgvAddFilters[e.ColumnIndex + 2, e.RowIndex].Value == null)
&& (dgvAddFilters[e.ColumnIndex, e.RowIndex + 2].Value == null)
&& (dgvAddFilters[e.ColumnIndex, e.RowIndex].Value != null))
{
dgvAddFilters.ContextMenuStrip = contMenuFilterMenu;
this.contMenuFilterMenu.Show(dgvAddFilters, relativeMousePosition);
}
else if ((e.ColumnIndex == 0)
&& (e.RowIndex > 0)
&& (dgvAddFilters[e.ColumnIndex, e.RowIndex + 2].Value == null)
&& (dgvAddFilters[e.ColumnIndex + 2, e.RowIndex].Value != null)
&& (dgvAddFilters[e.ColumnIndex, e.RowIndex].Value != null))
{
dgvAddFilters.ContextMenuStrip = contMenuOrEditDelete;
this.contMenuOrEditDelete.Show(dgvAddFilters, relativeMousePosition);
}
else if ((e.ColumnIndex == 0)
&& (e.RowIndex > 0)
&& (dgvAddFilters[e.ColumnIndex + 2, e.RowIndex].Value == null)
&& (dgvAddFilters[e.ColumnIndex, e.RowIndex + 2].Value != null)
&& (dgvAddFilters[e.ColumnIndex, e.RowIndex].Value != null))
{
dgvAddFilters.ContextMenuStrip = contMenuAndDeleteEditMenu;
this.contMenuAndDeleteEditMenu.Show(dgvAddFilters, relativeMousePosition);
}
else if ((dgvAddFilters[e.ColumnIndex, (e.RowIndex + 2)] != null)
&& (dgvAddFilters[(e.ColumnIndex + 2), e.RowIndex].Value != null)
&& (dgvAddFilters[e.ColumnIndex, e.RowIndex].Value != null))
{
dgvAddFilters.ContextMenuStrip = contmenuDeletEdit;
this.contmenuDeletEdit.Show(dgvAddFilters, relativeMousePosition);
}
else if ((dgvAddFilters[e.ColumnIndex, (e.RowIndex + 2)] != null)
&& (dgvAddFilters[e.ColumnIndex, e.RowIndex].Value != null))
{
dgvAddFilters.ContextMenuStrip = contMenuAndDeleteEditMenu;
this.contMenuAndDeleteEditMenu.Show(dgvAddFilters, relativeMousePosition);
}
else
{
return;
}
To know the type of cell that is clicked, You can try below way of doing.... See if it is helpful.
Get the clicked cell and check for its type.
Below is an example to check for checkbox type cell.
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
Type type = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].GetType();
if (type.Name == "DataGridViewCheckBoxCell")
{
string value = (string)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
}
}
Does this help you?
using System.ComponentModel;
using System.Windows.Forms;
namespace DGVCellTypes_47599159
{
public partial class Form1 : Form
{
DataGridView dgv = new DataGridView();
BindingList<dgventry> dgventries = new BindingList<dgventry>();
public Form1()
{
InitializeComponent();
InitOurStuff();
}
private void InitOurStuff()
{
this.Controls.Add(dgv);
dgv.Dock = DockStyle.Top;
dgv.DataSource = dgventries;
dgv.CellMouseDown += Dgv_CellMouseDown;
for (int i = 0; i < 10; i++)
{
dgventries.Add(new dgventry { col1 = $"col1_{i}", col2 = $"col2_{i}", col3 = (i % 2) > 0 });
}
}
private void Dgv_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (dgv.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewCheckBoxCell)
{
//do something
}
else if (dgv.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewTextBoxCell)
{
//do something
}
else if (dgv.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewImageCell)
{
//do something
}
else
{
//do something
}
}
}
public class dgventry
{
public string col1 { get; set; }
public string col2 { get; set; }
public bool col3 { get; set; }
}
}
I'm not getting how to find out whether the current cell is image cell or text box cell
private void Dgv_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (dgv.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewCheckBoxCell)
{
//do something
}
else if (dgv.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewTextBoxCell)
{
//do something
}
else if (dgv.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewImageCell)
{
//do something
}
else
{
//do something
}
}
I tried to get value of checked checkbox in DataGridView, so I check if value is true or false:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0 && e.RowIndex != -1)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if ((bool)dataGridView1.Rows[i].Cells["check"].Value == true)
{
dataGridView1.Rows[i].Cells["check"].Value = false;
}
else
{
dataGridView1.Rows[i].Cells["check"].Value = true;
}
button2.Enabled = (counter > 0);
}
}
}
}
It involks an error in line:
if ((bool)dataGridView1.Rows[i].Cells["check"].Value == true)
Second solution:
if (dataGridView1.Rows[i].Cells["check"].Value == null || (bool)dataGridView1.Rows[i].Cells["check"].Value == false)
{
dataGridView1.Rows[i].Cells["check"].Value = true;
counter++;
}
else
{
dataGridView1.Rows[i].Cells["check"].Value = false;
counter--;
}
The code below works, but sometimes checkbox is not checked
I am doing something really similar in a project of mine,
I am only using OnCellValueChanged instead of CellContentClick.
Here's my working line of code
bool completed = Convert.ToBoolean(dgv.Rows[e.RowIndex].Cells[1].Value.ToString());
What is exactly your error? Did you try to see what .Value was in the debugger ?
I'm trying to create a set-up interface for a program which simulates a board game in C#. I have 1 ComboBox which allows the user to select the number of players, which in turn hides or displays the selected number of comboboxes. Each combobox should initially have all four options (Red, Blue, Green, Yellow), however when a color is selected from one combobox, it should remove that option from the remaining comboboxes (i.e. if player1 selects Red, then players 2-4 should not also be able to select red). Right now I am trying to use multiple Lists to display the information in each combobox, but the code I have written to remove the colors from the remaining comboboxes has yielded a number of unintended consequences. I'm wondering if there is a better way in which to share the data between all of the comboboxes. Any help/ideas would be greatly appreciated!
I have attached my code below to give you a better idea of what I'm working with. Thank you for your time!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace StartPage.CS
{
public partial class SetUp : Form
{
// Create a static array to hold the players
public static Player[] players { get; private set; }
// create lists to hold the colors for each player
List<String> player1Colors = new List<String>();
List<String> player2Colors = new List<String>();
List<String> player3Colors = new List<String>();
List<String> player4Colors = new List<String>();
public SetUp()
{
InitializeComponent();
}
private void SetUp_Load(object sender, EventArgs e)
{
// initialize the selected index to 2 players
cboSelectPlayers.SelectedIndex = 0;
// add the colors to each list
player1Colors.Add("Red");
player1Colors.Add("Blue");
player1Colors.Add("Green");
player1Colors.Add("Yellow");
player2Colors.Add("Red");
player2Colors.Add("Blue");
player2Colors.Add("Green");
player2Colors.Add("Yellow");
player3Colors.Add("Red");
player3Colors.Add("Blue");
player3Colors.Add("Green");
player3Colors.Add("Yellow");
player4Colors.Add("Red");
player4Colors.Add("Blue");
player4Colors.Add("Green");
player4Colors.Add("Yellow");
// add each list to it's respective comboBox
for (int i = 0; i < player1Colors.Count; ++i)
{
cboPlayer1Color.Items.Add(player1Colors[i]);
}
for (int i = 0; i < player2Colors.Count; ++i)
{
cboPlayer2Color.Items.Add(player2Colors[i]);
}
for (int i = 0; i < player3Colors.Count; ++i)
{
cboPlayer3Color.Items.Add(player3Colors[i]);
}
for (int i = 0; i < player4Colors.Count; ++i)
{
cboPlayer4Color.Items.Add(player4Colors[i]);
}
}
// method to create the players and add them to the array
// handles displaying the number of players to select colors
private void cboSelectPlayers_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboSelectPlayers.SelectedIndex == 0) // if players = 2
{
lblPlayer3Select.Hide();
cboPlayer3Color.Hide();
lblPlayer4Select.Hide();
cboPlayer4Color.Hide();
}
else if (cboSelectPlayers.SelectedIndex == 1) // if players = 3
{
lblPlayer3Select.Show();
cboPlayer3Color.Show();
lblPlayer4Select.Hide();
cboPlayer4Color.Hide();
}
else if (cboSelectPlayers.SelectedIndex == 2) // if players 4
{
lblPlayer3Select.Show();
cboPlayer3Color.Show();
lblPlayer4Select.Show();
cboPlayer4Color.Show();
}
}
// handles removing player1's selected color from other comboboxes
private void cboPlayer1Color_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboPlayer1Color.SelectedItem == "Red")
{
// remove red from the other comboboxes
player2Colors.Remove("Red");
player3Colors.Remove("Red");
player4Colors.Remove("Red");
// make sure that the other colors that are supposed to be there are
if (!player2Colors.Contains("Blue") && !player3Colors.Contains("Blue") && !player4Colors.Contains("Blue"))
{
player2Colors.Add("Blue");
player3Colors.Add("Blue");
player4Colors.Add("Blue");
}
if (!player2Colors.Contains("Yellow") && !player3Colors.Contains("Yellow") && !player4Colors.Contains("Yellow"))
{
player2Colors.Add("Yellow");
player3Colors.Add("Yellow");
player4Colors.Add("Yellow");
}
if (!player2Colors.Contains("Green") && !player3Colors.Contains("Green") && !player4Colors.Contains("Green"))
{
player2Colors.Add("Green");
player3Colors.Add("Green");
player4Colors.Add("Green");
}
}
else if (cboPlayer1Color.SelectedItem == "Blue")
{
// remove blue from the other comboboxes
player2Colors.Remove("Blue");
player3Colors.Remove("Blue");
player4Colors.Remove("Blue");
// make sure that the other colors that are supposed to be there are
if (!player2Colors.Contains("Red") && !player3Colors.Contains("Red") && !player4Colors.Contains("Red"))
{
player2Colors.Add("Red");
player3Colors.Add("Red");
player4Colors.Add("Red");
}
if (!player2Colors.Contains("Yellow") && !player3Colors.Contains("Yellow") && !player4Colors.Contains("Yellow"))
{
player2Colors.Add("Yellow");
player3Colors.Add("Yellow");
player4Colors.Add("Yellow");
}
if (!player2Colors.Contains("Green") && !player3Colors.Contains("Green") && !player4Colors.Contains("Green"))
{
player2Colors.Add("Green");
player3Colors.Add("Green");
player4Colors.Add("Green");
}
}
else if (cboPlayer1Color.SelectedItem == "Yellow")
{
// remove yellow from the other comboboxes
player2Colors.Remove("Yellow");
player3Colors.Remove("Yellow");
player4Colors.Remove("Yellow");
// make sure that the other colors that are supposed to be there are
if (!player2Colors.Contains("Red") && !player3Colors.Contains("Red") && !player4Colors.Contains("Red"))
{
player2Colors.Add("Red");
player3Colors.Add("Red");
player4Colors.Add("Red");
}
if (!player2Colors.Contains("Blue") && !player3Colors.Contains("Blue") && !player4Colors.Contains("Blue"))
{
player2Colors.Add("Blue");
player3Colors.Add("Blue");
player4Colors.Add("Blue");
}
if (!player2Colors.Contains("Green") && !player3Colors.Contains("Green") && !player4Colors.Contains("Green"))
{
player2Colors.Add("Green");
player3Colors.Add("Green");
player4Colors.Add("Green");
}
}
else if (cboPlayer1Color.SelectedItem == "Green")
{
// remove green from the other comboboxes
player2Colors.Remove("Green");
player3Colors.Remove("Green");
player4Colors.Remove("Green");
// make sure that the other colors that are supposed to be there are
if (!player2Colors.Contains("Red") && !player3Colors.Contains("Red") && !player4Colors.Contains("Red"))
{
player2Colors.Add("Red");
player3Colors.Add("Red");
player4Colors.Add("Red");
}
if (!player2Colors.Contains("Blue") && !player3Colors.Contains("Blue") && !player4Colors.Contains("Blue"))
{
player2Colors.Add("Blue");
player3Colors.Add("Blue");
player4Colors.Add("Blue");
}
if (!player2Colors.Contains("Yellow") && !player3Colors.Contains("Yellow") && !player4Colors.Contains("Yellow"))
{
player2Colors.Add("Yellow");
player3Colors.Add("Yellow");
player4Colors.Add("Yellow");
}
}
// clear and then update the other comboboxes
cboPlayer2Color.Items.Clear();
cboPlayer3Color.Items.Clear();
cboPlayer4Color.Items.Clear();
for (int i = 0; i < player2Colors.Count; ++i)
{
cboPlayer2Color.Items.Add(player2Colors[i]);
}
for (int i = 0; i < player3Colors.Count; ++i)
{
cboPlayer3Color.Items.Add(player3Colors[i]);
}
for (int i = 0; i < player4Colors.Count; ++i)
{
cboPlayer4Color.Items.Add(player4Colors[i]);
}
}
// handles removing player2's selected color from other comboboxes
private void cboPlayer2Color_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboPlayer2Color.SelectedItem == "Red")
{
// remove red from the other comboboxes
player1Colors.Remove("Red");
player3Colors.Remove("Red");
player4Colors.Remove("Red");
// make sure that the other colors that are supposed to be there are
if (!player1Colors.Contains("Blue") && !player3Colors.Contains("Blue") && !player4Colors.Contains("Blue"))
{
player1Colors.Add("Blue");
player3Colors.Add("Blue");
player4Colors.Add("Blue");
}
if (!player1Colors.Contains("Yellow") && !player3Colors.Contains("Yellow") && !player4Colors.Contains("Yellow"))
{
player1Colors.Add("Yellow");
player3Colors.Add("Yellow");
player4Colors.Add("Yellow");
}
if (!player1Colors.Contains("Green") && !player3Colors.Contains("Green") && !player4Colors.Contains("Green"))
{
player1Colors.Add("Green");
player3Colors.Add("Green");
player4Colors.Add("Green");
}
}
else if (cboPlayer2Color.SelectedItem == "Blue")
{
// remove blue from the other comboboxes
player1Colors.Remove("Blue");
player3Colors.Remove("Blue");
player4Colors.Remove("Blue");
// make sure that the other colors that are supposed to be there are
if (!player1Colors.Contains("Red") && !player3Colors.Contains("Red") && !player4Colors.Contains("Red"))
{
player1Colors.Add("Red");
player3Colors.Add("Red");
player4Colors.Add("Red");
}
if (!player1Colors.Contains("Yellow") && !player3Colors.Contains("Yellow") && !player4Colors.Contains("Yellow"))
{
player1Colors.Add("Yellow");
player3Colors.Add("Yellow");
player4Colors.Add("Yellow");
}
if (!player1Colors.Contains("Green") && !player3Colors.Contains("Green") && !player4Colors.Contains("Green"))
{
player1Colors.Add("Green");
player3Colors.Add("Green");
player4Colors.Add("Green");
}
}
else if (cboPlayer2Color.SelectedItem == "Yellow")
{
// remove yellow from the other comboboxes
player1Colors.Remove("Yellow");
player3Colors.Remove("Yellow");
player4Colors.Remove("Yellow");
// make sure that the other colors that are supposed to be there are
if (!player1Colors.Contains("Red") && !player3Colors.Contains("Red") && !player4Colors.Contains("Red"))
{
player1Colors.Add("Red");
player3Colors.Add("Red");
player4Colors.Add("Red");
}
if (!player1Colors.Contains("Blue") && !player3Colors.Contains("Blue") && !player4Colors.Contains("Blue"))
{
player1Colors.Add("Blue");
player3Colors.Add("Blue");
player4Colors.Add("Blue");
}
if (!player1Colors.Contains("Green") && !player3Colors.Contains("Green") && !player4Colors.Contains("Green"))
{
player1Colors.Add("Green");
player3Colors.Add("Green");
player4Colors.Add("Green");
}
}
else if (cboPlayer2Color.SelectedItem == "Green")
{
// remove green from the other comboboxes
player1Colors.Remove("Green");
player3Colors.Remove("Green");
player4Colors.Remove("Green");
// make sure that the other colors that are supposed to be there are
if (!player1Colors.Contains("Red") && !player3Colors.Contains("Red") && !player4Colors.Contains("Red"))
{
player1Colors.Add("Red");
player3Colors.Add("Red");
player4Colors.Add("Red");
}
if (!player1Colors.Contains("Blue") && !player3Colors.Contains("Blue") && !player4Colors.Contains("Blue"))
{
player1Colors.Add("Blue");
player3Colors.Add("Blue");
player4Colors.Add("Blue");
}
if (!player1Colors.Contains("Yellow") && !player3Colors.Contains("Yellow") && !player4Colors.Contains("Yellow"))
{
player1Colors.Add("Yellow");
player3Colors.Add("Yellow");
player4Colors.Add("Yellow");
}
}
// clear and then update the other comboboxes
cboPlayer1Color.Items.Clear();
cboPlayer3Color.Items.Clear();
cboPlayer4Color.Items.Clear();
for (int i = 0; i < player2Colors.Count; ++i)
{
cboPlayer2Color.Items.Add(player2Colors[i]);
}
for (int i = 0; i < player3Colors.Count; ++i)
{
cboPlayer3Color.Items.Add(player3Colors[i]);
}
for (int i = 0; i < player4Colors.Count; ++i)
{
cboPlayer4Color.Items.Add(player4Colors[i]);
}
}
// handles removing player3's selected color from other comboboxes
private void cboPlayer3Color_SelectedIndexChanged(object sender, EventArgs e)
{
}
// handles removing player4's selected color from other comboboxes
private void cboPlayer4Color_SelectedIndexChanged(object sender, EventArgs e)
{
}
/* method to update the comboBoxes
private void updateComboBoxes()
{
for (int i = 0; i < player1Colors.Count; ++i)
{
cboPlayer1Color.Items.Add(player1Colors[i]);
}
for (int i = 0; i < player2Colors.Count; ++i)
{
cboPlayer2Color.Items.Add(player2Colors[i]);
}
for (int i = 0; i < player3Colors.Count; ++i)
{
cboPlayer3Color.Items.Add(player3Colors[i]);
}
for (int i = 0; i < player4Colors.Count; ++i)
{
cboPlayer4Color.Items.Add(player4Colors[i]);
}
}*/
private void btnStart_Click(object sender, EventArgs e)
{
//Control control = new Control(players);
GameBoard gameboard = new GameBoard();
gameboard.ShowDialog();
this.Close();
}
}
}
Here is how I ended up doing it (added a "Select" option to make it a little more logical in order to "unselect" a color):
List<string> colors = new List<string>() { "Select", "Red", "Blue", "Green", "Yellow" };
List<ComboBox> combos = new List<ComboBox>();
public Form1() {
InitializeComponent();
combos.AddRange(new ComboBox[] { comboBox1, comboBox2, comboBox3, comboBox4 });
foreach (ComboBox cb in combos) {
cb.Items.AddRange(colors.ToArray());
cb.SelectedIndex = 0;
cb.SelectedIndexChanged += cb_SelectedIndexChanged;
}
}
void cb_SelectedIndexChanged(object sender, EventArgs e) {
List<string> selectedColors = new List<string>();
foreach (ComboBox cb1 in combos) {
if (cb1.SelectedIndex > 0) {
selectedColors.Add(cb1.SelectedItem.ToString());
}
foreach (ComboBox cb2 in combos.Where(x => !x.Equals(cb1))) {
if (cb2.SelectedIndex > 0) {
if (cb1.Items.Contains(cb2.SelectedItem.ToString())) {
cb1.Items.Remove(cb2.SelectedItem.ToString());
}
}
}
}
foreach (ComboBox cb in combos) {
foreach (string c in colors) {
if (!selectedColors.Contains(c) && !cb.Items.Contains(c)) {
cb.Items.Add(c);
}
}
}
}
Basically, the logic is to get all of the colors that are selected into a list, then check if that color is showing up in the other lists, and if so, then remove it. Then you go back through the ComboBox items to see if any color is missing, and if so, add it back in.
In case anyone else happens upon this post, I wanted to post my code after including LarsTech's code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace StartPage.CS
{
public partial class SetUp : Form
{
// Create a static array to hold the players
public static Player[] players { get; private set; }
// create lists to hold the colors for each player, as well as the comboBoxes
List<String> colors = new List<String> { "Select Color","Red", "Blue", "Yellow", "Green" };
List<ComboBox> combos = new List<ComboBox>();
// constructor
public SetUp()
{
InitializeComponent();
// add colors to ComboBoxes and set the initial index
combos.AddRange(new ComboBox[] { cboPlayer1Color, cboPlayer2Color, cboPlayer3Color, cboPlayer4Color });
foreach (ComboBox combo in combos)
{
combo.Items.AddRange(colors.ToArray());
combo.SelectedIndex = 0;
combo.SelectedIndexChanged += combo_SelectedIndexChanged;
}
}
// eventhandling for form load
private void SetUp_Load(object sender, EventArgs e)
{
// initialize the selected index to 2 players
cboSelectPlayers.SelectedIndex = 0;
}
// handles displaying the number of players to select colors
private void cboSelectPlayers_SelectedIndexChanged(object sender, EventArgs e)
{
// reset each combobox to index 0
foreach (ComboBox cbox in combos)
{
cbox.SelectedIndex = 0;
}
// Hide or Show comboboxes based on how many players are selected
if (cboSelectPlayers.SelectedIndex == 0) // if players = 2
{
lblPlayer3Select.Hide();
cboPlayer3Color.Hide();
lblPlayer4Select.Hide();
cboPlayer4Color.Hide();
}
else if (cboSelectPlayers.SelectedIndex == 1) // if players = 3
{
lblPlayer3Select.Show();
cboPlayer3Color.Show();
lblPlayer4Select.Hide();
cboPlayer4Color.Hide();
}
else if (cboSelectPlayers.SelectedIndex == 2) // if players 4
{
lblPlayer3Select.Show();
cboPlayer3Color.Show();
lblPlayer4Select.Show();
cboPlayer4Color.Show();
}
}
// handles making sure that the same color can't be used by multiple players
public void combo_SelectedIndexChanged(object sender, EventArgs e)
{
List<String> selectedColors = new List<String>();
foreach (ComboBox cb1 in combos)
{
if (cb1.SelectedIndex > 0)
{
selectedColors.Add(cb1.SelectedItem.ToString());
}
foreach (ComboBox cb2 in combos.Where(x => !x.Equals(cb1)))
{
if (cb2.SelectedIndex > 0)
{
if (cb1.Items.Contains(cb2.SelectedItem.ToString()))
{
cb1.Items.Remove(cb2.SelectedItem.ToString());
}
}
}
}
foreach (ComboBox cb in combos)
{
foreach (String c in colors)
{
if (!selectedColors.Contains(c) && !cb.Items.Contains(c))
{
cb.Items.Add(c);
}
}
}
}
// handles form validation
private Boolean formValidation()
{
if (cboSelectPlayers.SelectedItem.ToString() == "2") // if number of players = 2
{
// display error message if one of the players hasn't selected a color and return false
if (cboPlayer1Color.SelectedIndex < 1 || cboPlayer2Color.SelectedIndex < 1)
{
MessageBox.Show("Please select a color for each player!");
return false;
}
else
{
players = new Player[2];
createPlayers(2);
}
}
else if (cboSelectPlayers.SelectedItem.ToString() == "3") // if number of players = 3
{
// display error message if one of the players hasn't selected a color and return false
if (cboPlayer1Color.SelectedIndex < 1 || cboPlayer2Color.SelectedIndex < 1 || cboPlayer3Color.SelectedIndex < 1)
{
MessageBox.Show("Please select a color for each player!");
return false;
}
else
{
players = new Player[3];
createPlayers(3);
}
}
else if (cboSelectPlayers.SelectedItem.ToString() == "4") // number of players = 4
{
// display error message if one of the players hasn't selected a color and return false
if (cboPlayer1Color.SelectedIndex < 1 || cboPlayer2Color.SelectedIndex < 1 || cboPlayer3Color.SelectedIndex < 1 || cboPlayer4Color.SelectedIndex < 1)
{
MessageBox.Show("Please select a color for each player!");
return false;
}
else
{
players = new Player[4];
createPlayers(4);
}
}
// if no errors were found in validation, return true
return true;
}
// create players and add them to the static array
private void createPlayers(int numPlayers)
{
for (int i = 0; i < numPlayers; i++)
{
if (combos[i].SelectedItem.ToString() == "Red")
{
players[i] = new Player(Color.Red);
}
else if (combos[i].SelectedItem.ToString() == "Blue")
{
players[i] = new Player(Color.Blue);
}
else if (combos[i].SelectedItem.ToString() == "Yellow")
{
players[i] = new Player(Color.Yellow);
}
else if (combos[i].SelectedItem.ToString() == "Green")
{
players[i] = new Player(Color.Green);
}
}
}
private void btnStart_Click(object sender, EventArgs e)
{
if (formValidation())
{
GameBoard gameboard = new GameBoard();
gameboard.ShowDialog();
this.Close();
}
}
}
}
How to make a xaml textbox in silverlight accept only numbers with maximum one decimal point precison. I have tried the answers in this question How to make a textBox accept only Numbers and just one decimal point in Windows 8. But it did not work. How can I do this ?
You can write a function like this,
txtDiscount.KeyDown += new KeyEventHandler(EnsureNumbers);
//Method to allow only numbers,
void EnsureNumbers(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
{
return;
}
bool result = EnsureDecimalPlaces();
if (result == false)
{
var thisKeyStr = "";
if (e.PlatformKeyCode == 190 || e.PlatformKeyCode == 110)
{
thisKeyStr = ".";
}
else
{
thisKeyStr = e.Key.ToString().Replace("D", "").Replace("NumPad", "");
}
var s = (sender as TextBox).Text + thisKeyStr;
var rStr = "^[0-9]+[.]?[0-9]*$";
var r = new Regex(rStr, RegexOptions.IgnoreCase);
e.Handled = !r.IsMatch(s);
}
else
{
e.Handled = true;
}
}
Method to ensure only 1 decimal,
bool EnsureDecimalPlaces()
{
string inText = txtDiscount.Text;
int decPointIndex = inText.IndexOf('.');
if (decPointIndex < 1 || decPointIndex == 1)
{
return false;
}
else
return true;
}
Esentially I'm trying to turn the below code into a loop. Every time I try to iterate through controls I seem to hit some sort of dead end and can't figure out how to update the relevant label or check the relevant textbox.
if (checkBox1.Checked && !string.IsNullOrEmpty(textBox1.Text))
{
if (RemoteFileExists(textBox1.Text) == true)
{
label1.Text = "UP";
}
else
{
label1.Text = "DOWN";
}
}
if (checkBox2.Checked && !string.IsNullOrEmpty(textBox2.Text))
{
if (RemoteFileExists(textBox2.Text) == true)
{
label2.Text = "UP";
}
else
{
label2.Text = "DOWN";
}
}
if (checkBox3.Checked && !string.IsNullOrEmpty(textBox3.Text))
{
if (RemoteFileExists(textBox3.Text) == true)
{
label3.Text = "UP";
}
else
{
label3.Text = "DOWN";
}
}
You can use Form.Controls to iterate all the controls on the page, so for example:
foreach(Control control in Controls) {
if (control is Checkbox) {
...
} else if (control is TextBox) {
...
} else {
...
}
}
However, this will do ALL controls so might not be efficient. You might be able to use the Tag of your controls and LINQ extensions to improve it, for example:
IEnumerable<Checkbox> needed_checkboxes = Controls.Where(control => control is Checkbox && control.Tag == someValue);
You can use it by finding the controls dynamically:
for (int i = 1; i < count; i++)
{
CheckBox chbx = (CheckBox) this.FindControl("checkBox" + i);
TextBox txtb = (TextBox)this.FindControl("textBox" + i);
Label lbl = (Label) this.FindControl("label" + i);
if (chbx.Checked && !string.IsNullOrEmpty(txtb.Text))
{
if (RemoteFileExists(txtb.Text) == true)
{
lbl.Text = "UP";
}
else
{
lbl.Text = "DOWN";
}
}
}