C# checkbox - c#

I have 3 check boxes in each row of 8 total rows. I want to have the third checkbox in each row to get checked only when the first two checkboxes are unchecked. I do not want to write a checkRow() method for each row.
What is the best way to go about it?
private void checkRow()
{
for (int i = 0; i < 8; i++)
{
var arraylist = new[] { checkbox1, checkbox2, checkbox3 };
if (checkbox1.Checked || checkbox2.Checked)
{
arraylist[2].Checked = false;
}
else
arraylist[2].Checked = true;
}
}
private void checbox1_CheckedChanged(object sender, EventArgs e)
{
checkRow();
}
private void checbox2_CheckedChanged(object sender, EventArgs e)
{
checkRow();
}
private void checbox3_CheckedChanged(object sender, EventArgs e)
{
checkRow();
}
In response.
private void checkRow()
{
var arraylist = new[] { checkEdit1, checkEdit2, checkEdit3 };
var arraylist1 = new[] { checkEdit4, checkEdit5, checkEdit6 };
var arraylist2 = new[] { checkEdit7, checkEdit8, checkEdit9 };
var array = new[] { arraylist, arraylist1, arraylist2 };
for (int i = 0; i < 8; i++)
{
//if checkedit1 or checkedit2 is checked the checkedit3 should not be checked
if (array[i]....Checked || array[i]....Checked)
{
arraylist[i]...Checked = false;
}
else
arraylist[i]...Checked = true;
}
}
I was trying to do something like this so that I dont have to write the checkRow() for each row

You should use the same method as the handler for all three delegates.
chkbox.CheckedChanged += new EventHandler(chkbox_CheckedChanged);
chkbox2.CheckedChanged += new EventHandler(chkbox_CheckedChanged);
chkbox3.CheckedChanged += new EventHandler(chkbox_CheckedChanged);
private void chkbox_CheckedChanged(object sender, EventArgs e)
{
// do your stuff here
}

Assuming you're not using a DataGridView or other way of organizing them into logical rows, why don't you do the following:
Store the checkboxes in an array so you have easy access to them.
CheckBox[,] checkArray = new CheckBox[8,3]...
Store the row index in the Tag property of the first and second checkboxes.
checkBox01.Tag = 0;
checkBox02.Tag = 0;
checkBox11.Tag = 1;
checkBox12.Tag = 1;
Have all the first and second checkboxes point to the same event handler:
checkBox01.CheckedChanged += new EventHandler(aCheckBox_CheckedChanged);
checkBox02.CheckedChanged += new EventHandler(aCheckBox_CheckedChanged);
checkBox11.CheckedChanged += new EventHandler(aCheckBox_CheckedChanged);
checkBox12.CheckedChanged += new EventHandler(aCheckBox_CheckedChanged);
In the event handler, you now know exactly which check box to update and no longer have to loop:
private void aCheckBox_CheckedChanged(object sender, EventArgs e)
{
int rowIndex = (int)((CheckBox)sender).Tag;
checkArray[rowIndex,2].Checked = !(checkArray[rowIndex,0].Checked ||
checkArray[rowIndex,1].Checked);
}
You can also do this using string lookups with the checkbox name, but it is surely slower and is a pain to refactor later if you choose to rename the checkboxes.

Related

How to get selected row value from C1FlexGrid

I have C1FlexGrid in my form with multiple rows. I want to select random rows and get those selected row value.
Selection Mode:
this.CliAcctHolderGrid.SelectionMode = C1.Win.C1FlexGrid.SelectionModeEnum.ListBox;
Function Code:
private void Submit(object sender, EventArgs e)
{
List<string> holderIdentificationId = new List<string>();
if (CliAcctHolderGrid.RowSel >= 1)
{
for (int CliAcctHolder = 1; CliAcctHolder <= CliAcctHolderGrid.Row; CliAcctHolder++)
{
C1.Win.C1FlexGrid.Row rowSel = CliAcctHolderGrid.Rows[CliAcctHolder];
holderIdentificationId.Add((string)rowSel["HolderIdentifierId"]);
}
}
}
From the code I have done, I am getting values which I didn't selected. Getting all values from the grid. Can anyone please suggest me where I am making a mistake.
private void Submit(object sender, EventArgs e)
{
List<string> holderIdentificationId = new List<string>();
if ( CliAcctHolderGrid.RowSel >= 1 )
{
foreach(C1.Win.C1FlexGrid.Row dr in CliAcctHolderGrid.Rows.Selected)
{
holderIdentificationId.Add( (string)dr["HolderIdentifierId"] );
}
}
}

Access Object created in another method C#

In this code I'm creating Few DataGridViews. Number of those depends on file which within each launch of application will be different, so is number of DataGridViews.
How can I Access particular dataGridView grid[i] and modify it from which event Form1_UserAddedRow was called in that method?
Code:
public void Form1_Load(object sender, EventArgs e)
{
string[] lines = System.IO.File.ReadAllLines(#"..\..\Base.txt");
int diet_num = 0;
int grid_num = 0;
foreach (string x in lines) diet_num++;
grid_num = (diet_num / Constant.DATAGRID_DIETS_IN_GRID) + 1;
DataGridView[] grid = new DataGridView[grid_num];
for (int i = 0; i < grid_num; i++)
{
grid[i] = new DataGridView();
grid[i].Tag = i;
grid[i].Parent = this;
grid[i].Location = new Point(12, 12 + (8 + Constant.DATAGRID_ROW_HEIGHT * 2) * i);
grid[i].Visible = true;
grid[i].RowHeadersVisible = false;
grid[i].Height = Constant.DATAGRID_ROW_HEIGHT * 2;
grid[i].Width = Constant.DATAGRID_COLUMN_SIZE * Constant.DATAGRID_DIETS_IN_GRID + 3;
grid[i].UserAddedRow += Form1_UserAddedRow;
}
this.Width = Constant.DATAGRID_COLUMN_SIZE * Constant.DATAGRID_DIETS_IN_GRID + 40;
foreach (string x in lines)
{
DataGridViewColumn col = new DataGridViewTextBoxColumn();
col.Width = Constant.DATAGRID_COLUMN_SIZE;
col.HeaderText = x;
int colIndex = grid[0].Columns.Add(col);
}
}
private void Form1_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
//I want to access grid[i] and modify it here.
}
You should be able to cast the Sender object parameter in your event handler to the type of DataGridView to retrieve the grid which has been effected.
You are getting the DataGridViewRowEventArgs e as the argument to your event handler and thus you can access the Row property like
e.Row.Cells["somename"].Value = "some_value";
private void Form1_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
var grid = sender as DataGridView;
if (grid == null) return;
//... do something
}

Min and max button and label

I'm trying to build a exam grader using C#. I'm new to this and don't know very much. What code would I use to add min and max buttons and to add a label stating whether it's a min or max?
private void btnAdd_Click(object sender, EventArgs e)
{
int points;
try
{
points = int.Parse(txtPoints.Text);
lstPoints.Items.Add(points);
txtPoints.Clear();
txtPoints.Focus();
if (lstPoints.Items.Count == 12)
{
txtPoints.Enabled = false;
btnAdd.Enabled = false;
}
if (lblResult.Text != "")
{
lblResult.Text = "";
}
}
catch
{
MessageBox.Show("Please enter only whole numbers");
txtPoints.Clear();
txtPoints.Focus();
}
}
private void btnAvg_Click(object sender, EventArgs e)
{
double total = 0;
for (int i = 0; i < lstPoints.Items.Count; i++)
{
total += (int)lstPoints.Items[i];
}
total /= lstPoints.Items.Count;
lblResult.Text = total.ToString();
}
private void btnClear_Click(object sender, EventArgs e)
{
lstPoints.Items.Clear();
txtPoints.Enabled = true;
btnAdd.Enabled = true;
}
}
}
hope this works
private void getMax()
{
int max=0;
for (int i = 0; i < lstPoints.Items.Count; i++)
{
if(max<(int)lstPoints.Items[i])
{
max=(int)lstPoints.Items[i];
}
}
lblResult.Text = max.ToString();
}
}
private void getMin()
{
int min=(int)lstPoints.Items[0];
for (int i = 1; i < lstPoints.Items.Count; i++)
{
if(min>(int)lstPoints.Items[i])
{
min=(int)lstPoints.Items[i];
}
}
lblResult.Text = min.ToString();
}
}
There are two possiblities as I see:
1) When you are writing this:
lstPoints.Items.Add(points);
Instead of adding to List(Of Integer) use SortedList. So the
list will always have the sorted result sets.
2) Use Array.Sort() to sort the records.
Once you have sorted records the first one is the minimum and the last one is the maximum (Assuming sorted in ascending order).
Take out two buttons and placed on the form, set Text Property from property window to Min and Max respectively and in event handler handle the Click event and pick the relevant resultset from lstPoints array.
Hope it helps!

how to store multiple selected listbox items in a session and view on another form?

The thing I want to do is that i want to select 1,2 or 3 items from the listbox and save them into a session and then display them all on another form in a listbox.
Here's my code!
This is my first post on stack overflow, so no hate please <3
//WebForm1
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lstProducts.Items.Add("Soap");
lstProducts.Items.Add("Schampoo");
lstProducts.Items.Add("Conditioner");
}
}
protected void cmdBuy_Click(object sender, EventArgs e)
{
string[] products = new string[3];
for (int i = 0; i < lstProducts.Items.Count; ++i)
{
if (lstProducts.Items[i].Selected)
products[i] = lstProducts.Items[i].Text;
else
products[i] = "0";
}
Session["Cart"] = products;
}
protected void cmdCart_Click(object sender, EventArgs e)
{
if (Session["Cart"] != null)
{
Response.Redirect("WebForm2.aspx");
}
}
}
//WebForm2
protected void Page_Load(object sender, EventArgs e)
{
string[] products = (string[])Session["Cart"];
for (int i = 0; i < 3; ++i)
{
if (products[i] != "0")
{
lstCart.Items.Add(products[i]);
}
}
}
}
}
The thing is that I only get the last selected item to display in the listbox on form2???
Try this
To store all items of the of the list box, you can add that items in array as:
string[] a = new string[]{"item 1","item 2","item 3"};
Session["values"] = a;
And in the next page, you can retrieve it like this.
string[] a = (string[])Session["values"]
EDIT #1
your case you can do like
ArrayList al = new ArrayList();
for (int i = 0; i < ListBox1.Items.Count; i++)
{
if (ListBox1.Items[i].Selected == true)
{
al.Add(ListBox1.Items[i].Value);
}
}
Session["selectedValues"] = al;
now you can use this sessiom variable in another page, but don't forget to cast in ArrayList type of object.

How can I get the array index of a given object in C# with control arrays?

I am dynamically adding a bunch of controls to a form. Each control calls the same method, and in that method I need to know the array index of the the control that performed the action.
CheckBox[] myCB = new CheckBox[100];
int i;
for (i = 0; i < 100; i++)
{
myCB[i] = new CheckBox();
myCB[i].Text = "Clicky!";
myCB[i].Click += new System.EventHandler(dynamicbutton_Click);
tableLayoutPanel1.Controls.Add(myCB[i]);
}
private void dynamicbutton_Click(Object sender, System.EventArgs e)
{
label1.Text = sender.???array index property???.ToString();
}
So if I click myCB[42] label1 will read "42" Of course, if there is an easier way to handle dynamic controls I'd appreciate pointers.
private void dynamicbutton_Click(Object sender, System.EventArgs e)
{
label1.Text = Array.IndexOf(myCB, (CheckBox)sender).ToString();
}
Control's should have a Tag property. Maybe you can attach the index to the Tag. You will incur boxing though...
int j = i;
myCB[i].Click += delegate(object sender, EventArgs e) {
// here you can use "j"
};
One obvious solution would be to set the tag:
CheckBox[] myCB = new CheckBox[100];
for (int i = 0; i < myCB.Length; i++)
{
myCB[i] = new CheckBox();
myCB[i].Text = "Clicky!";
myCB[i].Click += new System.EventHandler(dynamicbutton_Click);
myCB[i].Tag = i;
tableLayoutPanel1.Controls.Add(myCB[i]);
}
Then:
private void dynamicbutton_Click(Object sender, System.EventArgs e)
{
Control control = (Control) sender;
label1.Text = sender.Tag.ToString();
}
Another alternative is to capture the information in the event handler, most simply using a lambda expression or anonymous method:
CheckBox[] myCB = new CheckBox[100];
for (int i = 0; i < myCB.Length; i++)
{
int index = i; // This is very important, as otherwise i will
// be captured for all of them
myCB[i] = new CheckBox();
myCB[i].Text = "Clicky!";
myCB[i].Click += (s, e) => label1.Text = index.ToString();
tableLayoutPanel1.Controls.Add(myCB[i]);
}
or for more complicated behaviour:
CheckBox[] myCB = new CheckBox[100];
for (int i = 0; i < myCB.Length; i++)
{
int index= i; // This is very important, as otherwise i will
// be captured for all of them
myCB[i] = new CheckBox();
myCB[i].Text = "Clicky!";
myCB[i].Click += (s, e) => DoSomethingComplicated(index, s, e);
tableLayoutPanel1.Controls.Add(myCB[i]);
}
(where you declare DoSomethingComplicated appropriately).

Categories

Resources