Counting number of current checked boxes and output that number in c# - c#

I am trying to count the number of the current checked "checked box" in a group box. I have like 10 check boxes.
I been trying some code but I only managed to count upward if I checked the box but not the other way around. So it is only adding up (but not +1 each time).
So what approach do I have to take to count the number of the current (not incrementing) checked boxes? Thank you
int checkedBoxes = 0;
private void checkBox1_Click(object sender, EventArgs e)
{
CheckBox check = (CheckBox)sender;
bool result = check.Checked;
if (result == true)
{
btnDone.Enabled = true;
}
foreach (Control c in grpToppings.Controls)
{
CheckBox cb = c as CheckBox;
if (cb != null && cb.Checked)
{
checkedBoxes += 1;
int how_many = checkedBoxes;
}
}
}
private void btnDone_Click(object sender, EventArgs e)
{
string name = textbox_orderName.Text;
MessageBox.Show("\nhow many: " + checkedBoxes, "It is done",
MessageBoxButtons.OK);
}

Just move the assignment of checkedBoxes in the event checkBox1_Click as you are looping over all the child controls again and count should be reset.
int checkedBoxes;
private void checkBox1_Click(object sender, EventArgs e)
{
checkedBoxes = 0;
CheckBox check = (CheckBox)sender;
bool result = check.Checked;
if (result == true)
{
btnDone.Enabled = true;
}
foreach (Control c in grpToppings.Controls)
{
CheckBox cb = c as CheckBox;
if (cb != null && cb.Checked)
{
checkedBoxes += 1;
int how_many = checkedBoxes;
}
}
}

Related

C# DataGridViewComboBoxCell 2 kind of enter ( text and droplist ) when get focus value disappear

My datagridview have 6 comboboxcells, I would like those combobox can key number & select dropdownlist (On, Off). But I found when my comboboxcell get focus, the value will disappear. Now I select key text number to row[0]column[2], whenr I finish enter number and use "Enter" or mouse click to next row[1]column[2], therow[1]column[2] get focus, and the value I entered before will disappear. Why comboxcell get focus will disappear value?
text & dropdownlist data
next row get focus , the value disappear
Below are my code :
delegate void SetComboBoxCellType(int iRowIndex);
bool bIsComboBox = false;
private void datagridview_CellEnter(object sender, DataGridViewCellEventArgs e)
{
SetComboBoxCellType objChangeCellType = new SetComboBoxCellType(ChangeCellToComboBox);
if (e.ColumnIndex == this.datagridview.Columns[2].Index)
{
if (datagridview.CurrentRow.Cells[1].Value.ToString() == "Controlword")
{
this.datagridview.BeginInvoke(objChangeCellType, e.RowIndex);
bIsComboBox = false;
}
}
}
private void ChangeCellToComboBox(int iRowIndex)
{
if (bIsComboBox == false)
{
DataGridViewComboBoxCell dgComboCell = new DataGridViewComboBoxCell();
dgComboCell.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
dgComboCell.Items.Add("");
dgComboCell.Items.Add("ON");
dgComboCell.Items.Add("OFF");
datagridview.Rows[iRowIndex].Cells[datagridview.CurrentCell.ColumnIndex] = dgComboCell;
bIsComboBox = true;
}
}
private void datagridview_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 2 && e.FormattedValue != null)
{
var cell = this.datagridview.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewComboBoxCell;
if (cell != null && e.FormattedValue.ToString() != string.Empty && !cell.Items.Contains(e.FormattedValue))
{
cell.Items[0] = e.FormattedValue;
if (this.datagridview.IsCurrentCellDirty)
{
this.datagridview.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
cell.Value = e.FormattedValue;
}
}
}
private void datagridview_CellValidated(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex ==2)
{
NumericUpDown editingControl = this.datagridview.EditingControl as NumericUpDown;
if (editingControl != null)
{
editingControl.ValueChanged -= new EventHandler(myUpDownCtl_ValueChanged);
}
}
}
private void datagridview_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (datagridview.CurrentCell == datagridview[2, 0])
{
ComboBox cb = e.Control as ComboBox;
if (cb != null)
{
cb.SelectedIndexChanged -= Cb_SelectedIndexChanged;
// Following line needed for initial setup.
cb.DropDownStyle = cb.SelectedIndex == 0 ? ComboBoxStyle.DropDown : ComboBoxStyle.DropDownList;
cb.SelectedIndexChanged += Cb_SelectedIndexChanged;
}
}
}
private void Cb_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cb = sender as ComboBox;
cb.DropDownStyle = cb.SelectedIndex == 0 ? ComboBoxStyle.DropDown : ComboBoxStyle.DropDownList;
int selectedIndex = ((ComboBox)sender).SelectedIndex;
// MessageBox.Show("Selected Index = " + selectedIndex);
}

Maintaining state and count of checkboxes while paging in a GridView control

I have a gridview on a aspx page with pagination enabled.
This gridview contains some data fields from a database and a check-box for each row.
I started out wondering whether the check-box option will be remembered if I rebind the datasource before looping through all the rows, but quickly determined that even going from one page to the next page then back again the check-box option is lost.
To persist the check box checked status I have tried a custom implementation in this tutorial: http://aspalliance.com/774_Maintaining_State_of_CheckBoxes_While_Paging_in_a_GridView_Control.all
I want to count the number of checkboxes which are checked on my asp.net page and if the count = 5 then to change the button state from disabled to enabled, but when I change page in Gridview are not counted the selected rows of the grid in previous page.
My code it's below.
I would greatly appreciate any help you can give me in working this problem.
private void RememberOldValues()
{
ArrayList categoryIDList = new ArrayList();
int index = -1;
foreach (GridViewRow row in GridView1.Rows)
{
index = (int)GridView1.DataKeys[row.RowIndex].Value;
bool result = ((CheckBox)row.FindControl("chkSelect")).Checked;
if (Session["CHECKED_ITEMS"] != null)
categoryIDList = (ArrayList)Session["CHECKED_ITEMS"];
if (result)
{
if (!categoryIDList.Contains(index))
categoryIDList.Add(index);
}
else
categoryIDList.Remove(index);
}
if (categoryIDList != null && categoryIDList.Count > 0)
Session["CHECKED_ITEMS"] = categoryIDList;
}
private void RePopulateValues()
{
ArrayList categoryIDList = (ArrayList)Session["CHECKED_ITEMS"];
if (categoryIDList != null && categoryIDList.Count > 0)
{
foreach (GridViewRow row in GridView1.Rows)
{
int index = (int)GridView1.DataKeys[row.RowIndex].Value;
if (categoryIDList.Contains(index))
{
CheckBox myCheckBox = (CheckBox)row.FindControl("chkSelect");
myCheckBox.Checked = true;
}
}
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
RememberOldValues();
GridViewBind();
GridView1.DataSource = dset.Tables[0];
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
RePopulateValues();
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkTest = (CheckBox)sender;
GridViewRow grdRow = (GridViewRow)chkTest.NamingContainer;
int count = 0;
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("chkSelect");
if (chk.Checked)
{
count++;
grdRow.BackColor = System.Drawing.Color.Yellow;
}
}
if (count == 5)
{
btnUpdate.Enabled = true;
btnUpdate.CssClass = "enabledImageButton";
}
else
{
btnUpdate.Enabled = false;
btnUpdate.CssClass = "disabledImageButton";
}
}
Declare a private property to read arralist from session, to avoid calling it again and again.
ArrayList SelectedCategories
{
get
{
ArrayList categoryIDList;
if (Session["CHECKED_ITEMS"] != null)
categoryIDList = (ArrayList)Session["CHECKED_ITEMS"];
else
{
categoryIDList = new ArrayList();
Session["CHECKED_ITEMS"] = categoryIDList;
}
return categoryIDList;
}
}
Then in your Checkbox changed event you can change the code to access the stored selection array list.
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkTest = (CheckBox)sender;
GridViewRow grdRow = (GridViewRow)chkTest.NamingContainer;
int index = (int)GridView1.DataKeys[grdRow.RowIndex].Value;
if (chkTest.Checked)
{
if (!SelectedCategories.Contains(index))
SelectedCategories.Add(index);
grdRow.BackColor = System.Drawing.Color.Yellow;
}
else
{
if (SelectedCategories.Contains(index))
SelectedCategories.Remove(index);
grdRow.BackColor = System.Drawing.Color.White;
}
if (SelectedCategories.Count >= 5)
{
btnUpdate.Enabled = true;
btnUpdate.CssClass = "enabledImageButton";
}
else
{
btnUpdate.Enabled = false;
btnUpdate.CssClass = "disabledImageButton";
}
}

In datagridview how to use checkbox as radiobutton?

IDE: Visual Studio c#, Winforms Application.
I have invested around 12 hours but didn't get success. As DataGridView don't provide radiobutton type of cell. so i am trying to use checkbox cell as radio-buttion functionality.
i.e I want to be checked only one checkbox in a column.
see image:
It looks very simple thing but trust me it is not as simple as we are thinking. before giving reply please test the code.
Here are my sample tested code which i have tried:
code 1
////start
if (e.RowIndex != -1)
{
if (dataGridView1.Rows[e.RowIndex].Cells[0].Value != null && dataGridView1.CurrentCell.ColumnIndex == 0) //null check
{
if (e.ColumnIndex == 0)
{
if (((bool)dataGridView1.Rows[e.RowIndex].Cells[0].Value == true))
{
for (int k = 0; k <= 4; k++)
{
//uncheck all other checkboxes but keep the current as checked
if (k == dataGridView1.CurrentRow.Index)
{
dataGridView1.Rows[k].Cells[0].Value = false;
}
//if (gvTeam1.Rows[k].Cells[2].Selected != null)
//if(k !=e.RowIndex)
}
// gvTeam1.Rows[e.RowIndex].Cells[2].Value = false; // keep the current captain box checked
}
}
//}
// gvTeam1.Rows[rowPointerTeam1].Cells[2].Value = true;
}
}
//end
// here gvTeam1 is Datagridview1
code 2:
tested on datagridview1
private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 0)
{
for (int i = 0; i < 8; i++)
{
//if (i != dataGridView1.CurrentCell.RowIndex)
dataGridView1.Rows[i].Cells[0].Value = false;
}
dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value = true;
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//clean al rows
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.Cells["Select"].Value = false;
}
//check select row
dataGridView1.CurrentRow.Cells["Select"].Value = true;
}
I know I'm late to the party, but here is code to use actual radio buttons instead of checkboxes.
Credit:
Thanks to Arsalan Tamiz's blog post, on which this code is based.
http://arsalantamiz.blogspot.com/2008/09/using-datagridview-checkbox-column-as.html
Also thanks to M. Viper's answer for laying some of the ground work.
Step 1: Add a DataGridView control to your panel and add a CheckBoxColumn (I named mine grid and colRadioButton respectively). I'm not sure if this matters, but the EditMode property of my DataGridView is set to EditOnEnter.
Step 2: Create an event handler for the CellPainting event.
private void grid_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex == colRadioButton.Index && e.RowIndex >= 0)
{
e.PaintBackground(e.ClipBounds, true);
// TODO: The radio button flickers on mouse over.
// I tried setting DoubleBuffered on the parent panel, but the flickering persists.
// If someone figures out how to resolve this, please leave a comment.
Rectangle rectRadioButton = new Rectangle();
// TODO: Would be nice to not use magic numbers here.
rectRadioButton.Width = 14;
rectRadioButton.Height = 14;
rectRadioButton.X = e.CellBounds.X + (e.CellBounds.Width - rectRadioButton.Width) / 2;
rectRadioButton.Y = e.CellBounds.Y + (e.CellBounds.Height - rectRadioButton.Height) / 2;
ButtonState buttonState;
if (e.Value == DBNull.Value || (bool)(e.Value) == false)
{
buttonState = ButtonState.Normal;
}
else
{
buttonState = ButtonState.Checked;
}
ControlPaint.DrawRadioButton(e.Graphics, rectRadioButton, buttonState);
e.Paint(e.ClipBounds, DataGridViewPaintParts.Focus);
e.Handled = true;
}
}
Step 3: Handle the CurrentCellDirtyStateChanged event to uncheck the previous selection. This is basically the same as M. Viper's answer.
private void radioButtonChanged()
{
if (grid.CurrentCell.ColumnIndex == colRadioButton.Index)
{
foreach (DataGridViewRow row in grid.Rows)
{
// Make sure not to uncheck the radio button the user just clicked.
if (row.Index != grid.CurrentCell.RowIndex)
{
row.Cells[colRadioButton.Index].Value = false;
}
}
}
}
private void grid_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
radioButtonChanged();
}
Step 4: (Optional) Handle the CellClick event to allow the user to check the radio button by clicking anywhere in the cell rather than only directly on the radio button.
private void grid_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == colRadioButton.Index)
{
DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)grid.Rows[e.RowIndex].Cells[colRadioButton.Index];
cell.Value = true;
radioButtonChanged();
}
}
Try This,
private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
UpdateCellValue(e.RowIndex);
}
private void UpdateCellValue(int CurrentRowIndex)
{
if (CurrentRowIndex < 0)
return;
dataGridView1.Rows[CurrentRowIndex].Cells[0].Value = true;
dataGridView1.EndEdit();
if (CurrentRowIndex > -1)
{
for (int row = 0; row < dataGridView1.Rows.Count; row++)
{
if (CurrentRowIndex != row)
dataGridView1.Rows[row].Cells[0].Value = false;
}
}
}
Changing the default behavior of a control is undesired. We went through this path in one of my project and results were not fruitful. CheckBox control is used for multi-selection unlike the radio button. I would suggest you to write a custom RadioButtonCell for the DataGridView.
This Build a Custom RadioButton Cell and Column for the DataGridView Control article is nice place to start.
Paste this code on datagridview cellcontentclick and it will work as radio button
int row_index = e.RowIndex;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (row_index != i)
{
dataGridView1.Rows[i].Cells["Column1"].Value = false;
}
}
None of the answers worked for me, so:
private void MyDataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex > -1 && myDataGridView.Columns["MyRadioButtonColumnName"].Index == e.ColumnIndex)
{
int rowsCount = myDataGridView.Rows.Count - (myDataGridView.AllowUserToAddRows ? 1 : 0);
for (int rowIdx = 0; rowIdx < rowsCount; rowIdx++)
{
myDataGridView.Rows[rowIdx].Cells[e.ColumnIndex].Value = rowIdx == e.RowIndex;
}
}
}
private void MyDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex > -1 && myDataGridView.Columns["MyRadioButtonColumnName"].Index == e.ColumnIndex)
{
myDataGridView.CancelEdit();
}
}
private void MyDataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex > -1 && myDataGridView.Columns["MyRadioButtonColumnName"].Index == e.ColumnIndex)
{
bool isSelected = myDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected;
e.PaintBackground(e.ClipBounds, isSelected);
if (e.RowIndex < myDataGridView.Rows.Count - 1 || myDataGridView.AllowUserToAddRows == false)
{
bool isChecked = Convert.ToBoolean(myDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value) == true;
RadioButtonState state = isChecked ? RadioButtonState.CheckedNormal : RadioButtonState.UncheckedNormal; // using System.Windows.Forms.VisualStyles
RadioButtonRenderer.DrawRadioButton(e.Graphics, new Point(e.CellBounds.X + e.CellBounds.Width / 2 - 6, e.CellBounds.Y + e.CellBounds.Height / 2 - 6), state);
}
e.Handled = true;
}
}

Display the selected row from listview to textBox?

How to display the selected row from listview to textBox?
This is how I do int dataGridView:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.Rows[e.RowIndex].ReadOnly = true;
if (dataGridView1.SelectedRows.Count != 0)
{
DataGridViewRow row = this.dataGridView1.SelectedRows[0];
EmpIDtextBox.Text = row.Cells["EmpID"].Value.ToString();
EmpNametextBox.Text = row.Cells["EmpName"].Value.ToString();
}
}
I tried this:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
ListViewItem item = listView1.SelectedItems[0];
if (item != null)
{
EmpIDtextBox.Text = item.SubItems[0].Text;
EmpNametextBox.Text = item.SubItems[1].Text;
}
}
You may want to check if there is a SelectedItem first. When the selection changed, ListView would actually unselect the old item then select the new item, hence triggering listView1_SelectedIndexChanged twice. Other than that, your code should work:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
ListViewItem item = listView1.SelectedItems[0];
EmpIDtextBox.Text = item.SubItems[0].Text;
EmpNametextBox.Text = item.SubItems[1].Text;
}
else
{
EmpIDtextBox.Text = string.Empty;
EmpNametextBox.Text = string.Empty;
}
}
// select row listview check in c#
foreach (ListViewItem itemRow in taskShowListView.Items)
{
if (itemRow.Items[0].Checked == true)
{
int taskId = Convert.ToInt32(itemRow.SubItems[0].Text);
string taskDate = itemRow.SubItems[1].ToString();
string taskDescription = itemRow.SubItems[2].ToString();
}
}

Check/Uncheck a checkbox on datagridview

Can someone help me why it doesn't work?
I have a checkbox and if I click on it,
this should uncheck all the checkbox inside the datagridview which were checked before including the user selected checkbox.
Here is the code:
private void chkItems_CheckedChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in datagridview1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
if (chk.Selected == true)
{
chk.Selected = false;
}
else
{
chk.Selected = true;
}
}
}
the checkbox should not be selected. it should be checked.
here is the added column
DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn();
CheckBox chk = new CheckBox();
CheckboxColumn.Width = 20;
datagridview1.Columns.Add(CheckboxColumn);
Looking at this MSDN Forum Posting it suggests comparing the Cell's value with Cell.TrueValue.
So going by its example your code should looks something like this:(this is completely untested)
Edit: it seems that the Default for Cell.TrueValue for an Unbound DataGridViewCheckBox is null you will need to set it in the Column definition.
private void chkItems_CheckedChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
if (chk.Value == chk.TrueValue)
{
chk.Value = chk.FalseValue;
}
else
{
chk.Value = chk.TrueValue;
}
}
}
This code is working note setting the TrueValue and FalseValue in the Constructor plus also checking for null:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn();
CheckboxColumn.TrueValue = true;
CheckboxColumn.FalseValue = false;
CheckboxColumn.Width = 100;
dataGridView1.Columns.Add(CheckboxColumn);
dataGridView1.Rows.Add(4);
}
private void chkItems_CheckedChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
if (chk.Value == chk.FalseValue || chk.Value == null)
{
chk.Value = chk.TrueValue;
}
else
{
chk.Value = chk.FalseValue;
}
}
dataGridView1.EndEdit();
}
}
I was making my own version of a Checkbox to control a DataGridViewCheckBoxColumn when I saw this post wasn't actually answered. To set the checked state of a DataGridViewCheckBoxCell use:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
dataGridView1.Rows[row.Index].SetValues(true);
}
For anyone else trying to accomplish the same thing, here is what I came up with.
This makes the two controls behave like the checkbox column in Gmail. It keeps functionality for both mouse and keyboard.
using System;
using System.Windows.Forms;
namespace Check_UnCheck_All
{
public partial class Check_UnCheck_All : Form
{
public Check_UnCheck_All()
{
InitializeComponent();
dataGridView1.RowCount = 10;
dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvApps_CellContentClick);
this.dataGridView1.CellMouseUp += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.myDataGrid_OnCellMouseUp);
this.dataGridView1.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.myDataGrid_OnCellValueChanged);
this.checkBox1.Click += new System.EventHandler(this.checkBox1_Click);
}
public int chkInt = 0;
public bool chked = false;
public void myDataGrid_OnCellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == dataGridView1.Rows[0].Index && e.RowIndex != -1)
{
DataGridViewCheckBoxCell chk = dataGridView1.Rows[e.RowIndex].Cells[0] as DataGridViewCheckBoxCell;
if (Convert.ToBoolean(chk.Value) == true) chkInt++;
if (Convert.ToBoolean(chk.Value) == false) chkInt--;
if (chkInt < dataGridView1.Rows.Count && chkInt > 0)
{
checkBox1.CheckState = CheckState.Indeterminate;
chked = true;
}
else if (chkInt == 0)
{
checkBox1.CheckState = CheckState.Unchecked;
chked = false;
}
else if (chkInt == dataGridView1.Rows.Count)
{
checkBox1.CheckState = CheckState.Checked;
chked = true;
}
}
}
public void myDataGrid_OnCellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
// End of edition on each click on column of checkbox
if (e.ColumnIndex == dataGridView1.Rows[0].Index && e.RowIndex != -1)
{
dataGridView1.EndEdit();
}
dataGridView1.BeginEdit(true);
}
public void dgvApps_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.GetType() == typeof(DataGridViewCheckBoxCell))
{
if (dataGridView1.CurrentCell.IsInEditMode)
{
if (dataGridView1.IsCurrentCellDirty)
{
dataGridView1.EndEdit();
}
}
dataGridView1.BeginEdit(true);
}
}
public void checkBox1_Click(object sender, EventArgs e)
{
if (chked == true)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
if (chk.Value == chk.TrueValue)
{
chk.Value = chk.FalseValue;
}
else
{
chk.Value = chk.TrueValue;
}
}
chked = false;
chkInt = 0;
return;
}
if (chked == false)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
dataGridView1.Rows[row.Index].SetValues(true);
}
chked = true;
chkInt = dataGridView1.Rows.Count;
}
}
}
}
Simple code for you it will work
private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dgv.CurrentRow.Cells["ColumnNumber"].Value != null && (bool)dgv.CurrentRow.Cells["ColumnNumber"].Value)
{
dgv.CurrentRow.Cells["ColumnNumber"].Value = false;
dgv.CurrentRow.Cells["ColumnNumber"].Value = null;
}
else if (dgv.CurrentRow.Cells["ColumnNumber"].Value == null )
{
dgv.CurrentRow.Cells["ColumnNumber"].Value = true;
}
}
The code you are trying here will flip the states (if true then became false vice versa) of the checkboxes irrespective of the user selected checkbox because here the foreach is selecting each checkbox and performing the operations.
To make it clear, store the index of the user selected checkbox before performing the foreach operation and after the foreach operation call the checkbox by mentioning the stored index and check it (In your case, make it True -- I think).
This is just logic and I am damn sure it is correct. I will try to implement some sample code if possible.
Modify your foreach something like this:
//Store the index of the selected checkbox here as Integer (you can use e.RowIndex or e.ColumnIndex for it).
private void chkItems_CheckedChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in datagridview1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
if (chk.Selected == true)
{
chk.Selected = false;
}
else
{
chk.Selected = true;
}
}
}
//write the function for checking(making true) the user selected checkbox by calling the stored Index
The above function makes all the checkboxes true including the user selected CheckBox. I think this is what you want..
You can use this code on your grid CellClick event for check or unchecked cell checkbox :
private void Grid_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
Grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = (Grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null ? true : (!(bool)Grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value));
}
}
Try the below code it should work
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (checkBox2.Checked == false)
{
foreach (DataGridViewRow row in dGV1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
chk.Value = chk.TrueValue;
}
}
else if (checkBox2.Checked == true)
{
foreach (DataGridViewRow row in dGV1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
chk.Value = 1;
if (row.IsNewRow)
{
chk.Value = 0;
}
}
}
}
While all the other answers are correct, I'll add another simple option which worked for me:
var r = dataGridView.Rows[rIndex];
var c = r.Cells[cIndex];
var value = (bool) c.Value;
c.Value = !value;
Compressed:
var r = dataGridView.Rows[rIndex];
r.Cells[cIndex].Value = !((bool) r.Cells[cIndex].Value)
As long as cIndex refers to a cell that is of type DataGridViewCheckBoxCell, this will work fine. Hope this helps somone.
you can try this code:
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dataGridView1.CurrentRow.Cells[0];
dataGridView1.BeginEdit(true);
if (chk.Value == null || (int)chk.Value == 0)
{
chk.Value = 1;
}
else
{
chk.Value = 0;
}
dataGridView1.EndEdit();
Below Code is working perfect
Select / Deselect a check box column on data grid by using checkbox CONTROL
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (checkBox2.Checked == false)
{
foreach (DataGridViewRow row in dGV1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
chk.Value = chk.TrueValue;
}
}
else if(checkBox2.Checked==true)
{
foreach (DataGridViewRow row in dGV1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
chk.Value = 1;
if (row.IsNewRow)
{
chk.Value = 0;
}
}
}
}
// here is a simple way to do so
//irate through the gridview
foreach (DataGridViewRow row in PifGrid.Rows)
{
//store the cell (which is checkbox cell) in an object
DataGridViewCheckBoxCell oCell = row.Cells["Check"] as DataGridViewCheckBoxCell;
//check if the checkbox is checked or not
bool bChecked = (null != oCell && null != oCell.Value && true == (bool)oCell.Value);
//if its checked then uncheck it other wise check it
if (!bChecked)
{
row.Cells["Check"].Value = true;
}
else
{
row.Cells["Check"].Value = false;
}
}
I had the same problem, and even with the solutions provided here it did not work. The checkboxes would simply not change, their Value would remain null. It took me ages to realize my dumbness:
Turns out, I called the form1.PopulateDataGridView(my data) on the Form derived class Form1 before I called form1.Show(). When I changed up the order, that is to call Show() first, and then read the data and fill in the checkboxes, the value did not stay null.
The code bellow allows the user to un-/check the checkboxes in the DataGridView, if the Cells are created in code
private void gvData_CellClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)gvData.Rows[e.RowIndex].Cells[0];
if (chk.Value == chk.TrueValue)
{
gvData.Rows[e.RowIndex].Cells[0].Value = chk.FalseValue;
}
else
{
gvData.Rows[e.RowIndex].Cells[0].Value = chk.TrueValue;
}
}
Here is another example you can try
private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == dataGridView.Columns["Select"].Index)
{
dataGridView.EndEdit();
if ((bool)dataGridView.Rows[e.RowIndex].Cells["Select"].Value)
{
//-- checking current select, needs to uncheck any other cells that are checked
foreach(DataGridViewRow row in dataGridView.Rows)
{
if (row.Index == e.RowIndex)
{
dataGridView.Rows[row.Index].SetValues(true);
}
else
{
dataGridView.Rows[row.Index].SetValues(false);
}
}
}
}
}
All of the casting causes errors, nothing here I tried worked, so I fiddled around and got this to work.
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[0].Value != null && (bool)row.Cells[0].Value)
{
Console.WriteLine(row.Cells[0].Value);
}
}
I use the CellMouseUp event.
I check for the proper column
if (e.ColumnIndex == datagridview.Columns["columncheckbox"].Index)
I set the actual cell to a DataGridViewCheckBoxCell
dgvChkBxCell = datagridview.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
Then check to see if it's checked using EditingCellFormattedValue
if ((bool)dgvChkBxCell.EditingCellFormattedValue) { }
You will have to check for keyboard entry using the KeyUp event and check the .value property and also check that the CurrentCell's column index matches the checkbox column. The method does not provide e.RowIndex or e.ColumnIndex.
that worked for me after clearing selection, BeginEdit and change the girdview rows and end the Edit Mode.
if (dgvDetails.RowCount > 0)
{
dgvDetails.ClearSelection();
dgvDetails.BeginEdit(true);
foreach (DataGridViewRow dgvr in dgvDetails.Rows)
{
dgvr.Cells["cellName"].Value = true;
}
dgvDetails.EndEdit();
}
This is how I did it.
private void Grid_CellClick(object sender, DataGridViewCellEventArgs e)
{
if(Convert.ToBoolean(this.Grid.Rows[e.RowIndex].Cells["Selected"].Value) == false)
{
this.Grid.Rows[e.RowIndex].Cells["Selected"].Value = true;
}
else
{
this.productSpecGrid.Rows[e.RowIndex].Cells["Selected"].Value = false;
}
}

Categories