Can please any one help me on this. I have developed a c# windows application which has DataGridView first column has checkboxes. if I click on first column header it selects all the row level check boxes except the first row. For selecting all row level check boxes I have an event of dataGridView1_ColumnHeaderMouseClick and the code is:
private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
column.SortMode = DataGridViewColumnSortMode.NotSortable;
}
if (e.ColumnIndex == 0)
{
if (chek == 0)
{
try
{
for (int i = 0; i < dataGridView1.RowCount; i++)
{
string paymentValue = dataGridView1.Rows[i].Cells[18].Value.ToString();
string incmngp = dataGridView1.Rows[i].Cells[20].Value.ToString();
if (paymentValue == "N" && incmngp =="")
{
dataGridView1.Rows[i].Cells[0].Value = 1;
chek = 1;
}
}
if (chek == 1)
{
btn_update.Text = "Update";
}
}
catch (Exception ) { }
}
else if(chek==1)
{
try
{
for (int i = 0; i < dataGridView1.RowCount; i++)
{
dataGridView1.Rows[i].Cells[0].Value = 0;
chek = 0;
}
if (chek == 0)
{
btn_update.Text = "OK";
}
}
catch (Exception) { }
}
}
Note: chek is the variable declared on initialize stage
Set your Selection mode property of data grid view to ColumnHeaderSelect
and make sure all your 'Text' columns have SortMode set to NotSortable
UPDATE 2
In which case, Undo everything I ever told before and do that like this
Before you are assigning any DataTable to dataGridView1.
da.Fill(dt);
dataGridView1.DataSource = dt.DefaultView;
dataGridView1.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
foreach(DataGridViewColumn dc in dataGridView1.Columns)
{
dc.SortMode = DataGridViewColumnSortMode.NotSortable;
}
dataGridView1.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect;
UPDATE 3
Add an event handler for your dataGridView1's ColumnHeaderMouseClick Event
like below
Add the below code (Generic code if you want to use the same functionality for any column of check boxes)
private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
//Enter your own column index here
if(e.ColumnIndex == 0)
foreach(DataGridViewRow row in dataGridView1.Rows)
foreach (DataGridViewCell cell in row.Cells)
{
//Check if the cell type is of a CheckBoxCell
if (cell.GetType() == typeof(DataGridViewCheckBoxCell))
{
DataGridViewCheckBoxCell c = (DataGridViewCheckBoxCell)cell;
c.TrueValue = "T";
c.FalseValue = "F";
if (c.Value == c.FalseValue|| c.Value == null )
c.Value = c.TrueValue;
else
c.Value = c.FalseValue;
}
}
dataGridView1.RefreshEdit();
}
This is a very bizarre bug in Winforms. The problem more generally applies not to the first row, but to the first selected cell in any row of DataGridViewCheckBoxCell(s). You can select the CheckBox cell by clicking on the check box, or select the cell outside the check box, the behavior is the same. If you select 3 check boxes in the middle of your grid, the first of those three will freeze and not update properly. If you try to clear the selection in code, with a dataGridView1.ClearSelection() method call, it still does not work.
The correct answer is to call datagridview1.RefreshEdit() right after you change the checkbox data. You can't just call it after all changes are made. It must be made for each change in the CheckBox value.
foreach (DataGridViewRow row in Results.Rows)
{
var ck = (DataGridViewCheckBoxCell) row.Cells["check"];
ck.Value = ck.TrueValue;
Results.RefreshEdit();
}
My requirement : In datagridview I need select row by clicking the row header and selected row should maintain until I will click the other row header also same time I should select cell too.
My Problem : I can't select multiple row using Shift and Ctrl key.
my code :
List< DataGridViewRow> selectedRows = new List< DataGridViewRow>();
void selectRows()
{
dataGridView1.SuspendLayout();
foreach (DataGridViewRow r in dataGridView1.Rows)
{
r.Selected = selectedRows.Contains(r);
}
dataGridView1.ResumeLayout();
}
private void dataGridView1_RowHeaderMouseClick(object sender,DataGridViewCellMouseEventArgs e)
{
DataGridViewRow clickedRow = dataGridView1.CurrentRow;
if (selectedRows.Contains(clickedRow))
{
selectedRows.Remove(clickedRow);
}
else
{
selectedRows.Add(clickedRow);
}
selectRows();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((row.Index != e.RowIndex) && !row.Selected)
{
row.DefaultCellStyle.BackColor = Color.White;
}
else
{
selectedRows.Remove(clickedRow);
row.Selected = true;
row.DefaultCellStyle.BackColor = Color.Blue;
}
}
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.DefaultCellStyle.BackColor == Color.Blue)
{
row.Selected = true;
}
}
}
You have to set your enable your datagridview's multiselect dataGridView.MultiSelect = true;
Be familiar with using a debugger, you will be able to find out where the issue is.
You are clearing the selection in your loop
foreach (DataGridViewRow row in dataGridView1.Rows)
{
}
Rethink the if-else logic in it and you will see why. You are clearing your previous selections when you are not suppose to.
I have 2 DataGridView controls on a form. Both have same number and types of columns. 1 TextBox Column and 2 CheckBoxColumns.
The Problem is that first DataGridView is working fine but the other one is not. both have same binding methods and datasource. The problems with the second DataGridView on the same form are..
Checkbox values are not set
currentrow.Tag value is null when I try to retrieve the value
Below is the code i'm using to bind the DataGridViews and setting checkbox values
public void BindGridView(DataGridView gv)
{
var actuallist = UserOperations.GetPermissions(RoleId, (int)(Enumerations.ModuleType.Basic));
Common.Common.StyleGridView(gv);
gv.AutoGenerateColumns = false;
gv.Columns["ModuleName"].DataPropertyName = "ModuleName";
gv.DataSource = actuallist;
int j = 0;
foreach (DataGridViewRow row in gv.Rows)
{
row.Tag = actuallist[j++].ModuleId;
}
int k = 0;
bool r = false;
foreach (DataGridViewRow row in gv.Rows)
{
r = actuallist[k++].PermissionGranted;
if (r)
((DataGridViewCheckBoxCell)row.Cells[1]).Value = r;
else
((DataGridViewCheckBoxCell)row.Cells[2]).Value = !r;
}
}
private void gvPermissions_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (gvPermissions.Columns[e.ColumnIndex].Name == "Granted")
{
bool isChecked = (bool)gvPermissions[e.ColumnIndex, e.RowIndex].EditedFormattedValue;
gvPermissions.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = !isChecked;
gvPermissions.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].Value = isChecked;
gvPermissions.EndEdit();
}
if (gvPermissions.Columns[e.ColumnIndex].Name == "Denied")
{
bool isChecked = (bool)gvPermissions[e.ColumnIndex, e.RowIndex].EditedFormattedValue;
gvPermissions.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = !isChecked;
gvPermissions.Rows[e.RowIndex].Cells[e.ColumnIndex - 1].Value = isChecked;
gvPermissions.EndEdit();
}
}
I want to uncheck all selected CheckBoxes from DataGridView which is generated dynamically?
I tried like following
for (int i = 0; i < MygridView.Rows.Count; i++)
{
DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)MygridView.Rows[i].Cells[0];
if (cell.Value == cell.TrueValue)
{
// (row.Cells[CheckBoxColumn.Index] as DataGridViewCheckBoxCell).value = false;
Need to unchecked all checked checkboxes
}
}
Or Is there any other method?
Try this:
foreach (DataGridViewRow item in MygridView)
{
DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)item.Cells[0];
cell.Value = false;
}
I've added a checkbox column to a DataGridView in my C# form. The function needs to be dynamic - you select a customer and that brings up all of their items that could be serviced, and you select which of them you wish to be serviced this time around.
Anyway, the code will now add a chckbox to the beginning of the DGV. What I need to know is the following:
1) How do I make it so that the whole column is "checked" by default?
2) How can I make sure I'm only getting values from the "checked" rows when I click on a button just below the DGV?
Here's the code to get the column inserted:
DataGridViewCheckBoxColumn doWork = new DataGridViewCheckBoxColumn();
doWork.HeaderText = "Include Dog";
doWork.FalseValue = "0";
doWork.TrueValue = "1";
dataGridView1.Columns.Insert(0, doWork);
So what next?
Any help would be greatly appreciated!
There is no way to do that directly. Once you have your data in the grid, you can loop through the rows and check each box like this:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.Cells[CheckBoxColumn1.Name].Value = true;
}
The Click event might look something like this:
private void button1_Click(object sender, EventArgs e)
{
List<DataGridViewRow> rows_with_checked_column = new List<DataGridViewRow>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (Convert.ToBoolean(row.Cells[CheckBoxColumn1.Name].Value) == true)
{
rows_with_checked_column.Add(row);
}
}
// Do what you want with the check rows
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewCheckBoxCell ch1 = new DataGridViewCheckBoxCell();
ch1 = (DataGridViewCheckBoxCell)dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0];
if (ch1.Value == null)
ch1.Value=false;
switch (ch1.Value.ToString())
{
case "True":
ch1.Value = false;
break;
case "False":
ch1.Value = true;
break;
}
MessageBox.Show(ch1.Value.ToString());
}
best solution to find if the checkbox in the datagridview is checked or not.
it took me a long time to figure out how to do this without having to loop through all the records. I have a bound datagridview-source, and all fields are bound except for the checkbox-column. So I don't have/need a loop to add each row and I didn't want to create one just for this purpuse. So after a lot of trying I finally got it. And it's actually very simple too:
First you add a new .cs File to your project with a custom-checkbox cell, e.g.
DataGridViewCheckboxCellFilter.cs:
using System.Windows.Forms;
namespace MyNamespace {
public class DataGridViewCheckboxCellFilter : DataGridViewCheckBoxCell {
public DataGridViewCheckboxCellFilter() : base() {
this.FalseValue = 0;
this.TrueValue = 1;
this.Value = TrueValue;
}
}
}
After this, on your GridView, where you add the checkbox-column, you do:
// add checkboxes
DataGridViewCheckBoxColumn col_chkbox = new DataGridViewCheckBoxColumn();
{
col_chkbox.HeaderText = "X";
col_chkbox.Name = "checked";
col_chkbox.CellTemplate = new DataGridViewCheckboxCellFilter();
}
this.Columns.Add(col_chkbox);
And that's it! Everytime your checkboxes get added in a new row, they'll be set to true.
Enjoy!
Here's a one liner answer for this question
List<DataGridViewRow> list = DataGridView1.Rows.Cast<DataGridViewRow>().Where(k => Convert.ToBoolean(k.Cells[CheckBoxColumn1.Name].Value) == true).ToList();
If you try it on CellContentClick Event
Use:
dataGridView1.EndEdit(); //Stop editing of cell.
MessageBox.Show("0 = " + dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
If you have a gridview containing more than one checkbox ....
you should try this ....
Object[] o=new Object[6];
for (int i = 0; i < dgverlist.RowCount; i++)
{
for (int j = 2; j < dgverlist.ColumnCount; j++)
{
DataGridViewCheckBoxCell ch1 = new DataGridViewCheckBoxCell();
ch1 = (DataGridViewCheckBoxCell)dgverlist.Rows[i].Cells[j];
if (ch1.Value != null)
{
o[i] = ch1.OwningColumn.HeaderText.ToString();
MessageBox.Show(o[i].ToString());
}
}
}
1) How do I make it so that the whole column is "checked" by default?
var doWork = new DataGridViewCheckBoxColumn();
doWork.Name = "IncludeDog" //Added so you can find the column in a row
doWork.HeaderText = "Include Dog";
doWork.FalseValue = "0";
doWork.TrueValue = "1";
//Make the default checked
doWork.CellTemplate.Value = true;
doWork.CellTemplate.Style.NullValue = true;
dataGridView1.Columns.Insert(0, doWork);
2) How can I make sure I'm only getting values from the "checked" rows?
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.IsNewRow) continue;//If editing is enabled, skip the new row
//The Cell's Value gets it wrong with the true default, it will return
//false until the cell changes so use FormattedValue instead.
if (Convert.ToBoolean(row.Cells["IncludeDog"].FormattedValue))
{
//Do stuff with row
}
}
To test if the column is checked or not:
for (int i = 0; i < dgvName.Rows.Count; i++)
{
if ((bool)dgvName.Rows[i].Cells[8].Value)
{
// Column is checked
}
}
if u make this column in sql database (bit) as a data type u should edit this code
DataGridViewCheckBoxColumn doWork = new DataGridViewCheckBoxColumn();
doWork.HeaderText = "Include Dog";
doWork.FalseValue = "0";
doWork.TrueValue = "1";
dataGridView1.Columns.Insert(0, doWork);
with this
DataGridViewCheckBoxColumn doWork = new DataGridViewCheckBoxColumn();
doWork.HeaderText = "Include Dog";
doWork.FalseValue = "False";
doWork.TrueValue = "True";
dataGridView1.Columns.Insert(0, doWork);
It is quite simple
DataGridViewCheckBoxCell checkedCell = (DataGridViewCheckBoxCell) grdData.Rows[e.RowIndex].Cells["grdChkEnable"];
bool isEnabled = false;
if (checkedCell.AccessibilityObject.State.HasFlag(AccessibleStates.Checked))
{
isEnabled = true;
}
if (isEnabled)
{
// do your business process;
}
If your column has been already created due to binding with a recordset of BIT type, the type of the column will be text anyway. The solution I have found is to remove that column and replace it with a DataGridViewCheckBoxColumn having the same binding data.
DataGridViewColumn oldCol = dgViewCategory.Columns["mycolumn"];
int chkIdx = oldCol.Index;
DataGridViewCheckBoxColumn chkCol = new DataGridViewCheckBoxColumn();
chkCol.HeaderText = oldCol.HeaderText;
chkCol.FalseValue = "False";
chkCol.TrueValue = "True";
chkCol.DataPropertyName = oldCol.DataPropertyName;
chkCol.Name = oldCol.Name;
dgViewCategory.Columns.RemoveAt(chkIdx);
dgViewCategory.Columns.Insert(chkIdx, chkCol);