Programmatically uncheck checkboxcolumn in datagridview - c#

How can I programmatically uncheck all rows in a DataGridViewCheckboxColumn in a datagridview?
I can get the correct value of the checkbox using
(bool)row.Cells[CheckBoxColumn.Index].FormattedValue
but that's only a getter.
I have tried setting the value of the cell using
(bool)row.Cells[CheckBoxColumn.Index].value = false
but that doesn't affect the FormattedValue.
How can I solve this?

You do sth. like:
(row.Cells[CheckBoxColumn.Index] as DataGridViewCheckBoxCell).value = false;
You just forgot to cast to the correct type, a generic DataGridViewCell doesn't know its value-type.

Have you tried casting the first control in the checkbox column to checkbox and then setting 'Checked' to true?
Try something to this extent.
((DataGridViewCheckBoxCell)e.Rows[0].Cells[0]).Selected = true

you should just use YourDataGridview.EndEdit() after checking.
(row.Cells[CheckBoxColumn.Index] as DataGridViewCheckBoxCell).value = false;
YourDataGridview.EndEdit();

Haven't checked but you can try;
CheckBox cb = (row.Cells[CheckBoxColumn.Index].Controls[0] as CheckBox);
if(cb != null)
{
cb.Checked = false;
}
It's type may be different. Just debug and cast it to what it is.

foreach (DataGridViewRow dr in dataGridView1.Rows)
{
dr.Cells[0].Value = true;//sıfırın
}

If you use dataGridView1_ContextClick just for do "false" datagidviewCheckBox Column need this Code :
dataGridView1.CancelEdit();
but if you need all rows of CheckBoxColumns of DataGrid :
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow r in dataGridView1.Rows)
{
r.Cells["statusBox"].Value = true;
}
}

Depending on what you wish to do
If it is about the selected row, then you can:
DataGridViewRow row = dataGridViewName.CurrentRow;
//This will assign the opposite value of the Cell Content
row.Cells["ColumnName"].Value = !Convert.ToBoolean(row.Cells["ColumnName"].Value);
However if you wish to do it for the whole DataGridView table then:
foreach (DataGridViewRow row in dataGridViewName.Rows)
{
//This will assign the opposite value of the Cell Content
row.Cells["ColumnName"].Value = !Convert.ToBoolean(row.Cells["ColumnName"].Value);
}
Whatever suites you. Keep it up!

Loop through each row of grid view and use the find control method:
foreach ( GridViewRow row in myGridView )
{
CheckBox checkBox = ( CheckBox ) row.FindControl( "myCheckBox" );
checkbox.Checked = false;
}

foreach (DataGridViewRow row in datagridviewname.Rows)
{
row.Cells[CheckBoxColumn1_Name].Value = false;
}

Related

How to get datagridviewcheckboxcolumn value c#?

In my window form application I have a datagridview which has a checkbox column I want to retrieve its value is checked or not I attempted
if ((bool)dataGridView1[columnindex,rowindex].Value ==true )
{
MessageBox.show ("checked");
}
but it doesn't work
please answer me
This should works fine:
var value = dataGridView1[columnindex, rowindex].Value
So if you said "it doesn't work" - than just you need to provide us more information about error you got, etc.
You can try following code snippet
foreach (DataGridViewRow roow in dataGridView1.Rows)
{
DataGridViewCheckBoxCell chkchecking = roow.Cells[0] as DataGridViewCheckBoxCell;
if (Convert.ToBoolean(chkchecking.Value) == true)
{
}
}
DataGridViewCheckBoxCell checkbox = (DataGridViewCheckBoxCell)dataGridView1.CurrentCell;
bool ischecked = (bool)checkbox.EditedFormattedValue;
if (ischecked == true)
{
MessageBox.Show("True")
}
this code can get datagridview checkbox cell value

Programming gridview checkboxes to auto check relevant rows

I want to program the checkboxes so that if a row is selected, the program will read the value in the first column of the gridview row and automatically check all rows that also have that value in their first column. I was able to do this using an array to store the value and running through each row, checking if this value was a match. If it matched, the checkbox was checked. This worked but was a very limited solution. When I tried to reverse the action, it simply rechecked that value automatically because that value was still in the array and I did not know how to distinguish between a check or un-check action. It was solely based on a change event.
int count = 0;
foreach (GridViewRow gvrow in GridView1.Rows)
{
CheckBox chk = (CheckBox)gvrow.FindControl("chkRow");
if (chk.Checked)
{
count++;
}
}
string [] dnum = new string[count];
int counter = 0;
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox myCheckBox = row.FindControl("chkRow") as CheckBox;
if (myCheckBox.Checked)
{
if (counter > 0)
{
int number = counter - 1;
if (row.Cells[1].Text != dnum[number])
{
dnum[counter] = row.Cells[1].Text;
counter++;
}
}
else
{
dnum[counter] = row.Cells[1].Text;
counter++;
}
}
}
return dnum;
}
The array dnum should return the first column values for the checked rows . With this I can run through each row and check if any checkboxes need to be checked.
foreach (GridViewRow gvrow in GridView1.Rows)
{
CheckBox ChkBox = (CheckBox)gvrow.FindControl("chkRow");
if (ChkBox.Checked == true)
{
foreach (string s in first)
{
if (gvrow.Cells[1].Text == s)
{
ChkBox.Checked = true;
}
}
}
But now I am unable to figure out how to reverse the process, i.e when I uncheck one, all with the same first column value must uncheck, instead it just rechecks because that value is still in the array. I am open to completely different methods.
Many thanks,
Nicolas
I don't clearly understand your problem, Maybe you're looking for this?
use this code instead of your old one in check ChkBox loop.
if (gvrow.Cells[1].Text == s)
{
ChkBox.Checked = !ChkBox.Checked;
}
With ChkBox.Checked = !ChkBox.Checked, It'll reverse value in checkbox.
If it was true, It'll become false. If it was false, It'll become true.
Will just give another example, not sure on how you are implementing at your code so here it goes...
For example you have your gridview as below:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1"
OnCheckedChanged="CheckBox1_Click"
AutoPostBack="True" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And in your code behind..
mockData data below is just sample data for our gridview to demonstrate the check and un-check of same value based on selected checkbox property and column[1] value.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var mockData = new[] {"1", "1", "2", "1", "3", "2"};
GridView1.DataSource = mockData;
GridView1.DataBind();
}
}
protected void CheckBox1_Click(object sender, EventArgs e)
{
var chkBox = (CheckBox) sender;
var selectedRow = chkBox.Parent.Parent;
var itemValue = ((GridViewRow)selectedRow).Cells[1].Text;
foreach (var chkItem in GridView1.Rows.Cast<GridViewRow>()
.Where(item => item.Cells[1].Text == itemValue)
.Select(item => item.Cells[0].FindControl("CheckBox1")).OfType<CheckBox>())
{
chkItem.Checked = chkBox.Checked;
}
}
}
If I click on checkbox in one row with value of "1", All rows with value of "1" should be automatically set to the property of selected checkbox.
Let me know if I misunderstood your requirement. You can apply to your code and let me know if it works :-) cheers.

Can DataGridRow validation done for single element of row?

public static bool _isvalid = true ;
public static void onhaschgd(DependencyObject obj,DependencyPropertyChangedEventArgs args)
{
DataGridRow dgr = (DataGridRow)obj
_isValid = (dgr !=null && Validation.GetHasError())?false:true
}
Basically my need is to validate only certain items of row, but the validation occurs as a whole row. Is there any way that I can select specific row item and do validation? Like row.item['myfieldname'] something?
Enumerate round the columns of each row and validate when you get to the one you want:
foreach (DataGridColumn col in DG1.Columns)
{
col.Visibility = Visibility.Visible;
}
https://msdn.microsoft.com/en-us/library/system.windows.controls.datagrid.columns(v=vs.100).aspx

Default value always display blank when bind a datasource to a DataGridViewComboBoxColumn

This is my code:
DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.ValueMember = "Value";
col.DisplayMember = "Name";
col.DataSource = lstParameterDataSource;
//lstParameterDataSource is lst like List<BindEntity>.
The BindEntity is a class which has two property. One property is Value, and the other one is Name. Both of them are string type.
this.dgvCondition.RowsAdded += delegate(object sender, DataGridViewRowsAddedEventArgs args)
{
if (this._parameters != null && this._parameters.Count > 0)
{
DataGridViewComboBoxCell cell = this.dgvCondition.Rows[args.RowIndex].Cells[0] as DataGridViewComboBoxCell;
cell.Value = lstParameterDataSource[0].Value;
}
};
dgvCondition is my datagridview which user will be edited. In addition I handle the event RowsAdded of gvCondition so that display a default value in datagridview when user adding a new row.
When I add this col to my dgvCondition, and then add a row on it. It always show a empty cell except I select a value by myself. I tried to debug this app, and I found that code cell.Value = lstParameterDataSource[0].Value; didn't work. The cell's Value is always null.
What is going on? I want it show a default value when UI show. How can I implement this function?
You can use this,
((DataGridViewComboBoxCell)(this.dgvCondition.Rows[args.RowIndex].Cells[0])).Value= lstParameterDataSource[0].Value;
let me know if u help this.

Selecting a row in DataGridView programmatically

How can I select a particular range of rows in a DataGridView programmatically at runtime?
Not tested, but I think you can do the following:
dataGrid.Rows[index].Selected = true;
or you could do the following (but again: not tested):
dataGrid.SelectedRows.Clear();
foreach(DataGridViewRow row in dataGrid.Rows)
{
if(YOUR CONDITION)
row.Selected = true;
}
In Visual Basic, do this to select a row in a DataGridView; the selected row will appear with a highlighted color but note that the cursor position will not change:
Grid.Rows(0).Selected = True
Do this change the position of the cursor:
Grid.CurrentCell = Grid.Rows(0).Cells(0)
Combining the lines above will position the cursor and select a row. This is the standard procedure for focusing and selecting a row in a DataGridView:
Grid.CurrentCell = Grid.Rows(0).Cells(0)
Grid.Rows(0).Selected = True
DataGridView.Rows
.OfType<DataGridViewRow>()
.Where(x => (int)x.Cells["Id"].Value == pId)
.ToArray<DataGridViewRow>()[0]
.Selected = true;
<GridViewName>.ClearSelection(); ----------------------------------------------------1
foreach(var item in itemList) -------------------------------------------------------2
{
rowHandle =<GridViewName>.LocateByValue("UniqueProperty_Name", item.unique_id );--3
if (rowHandle != GridControl.InvalidRowHandle)------------------------------------4
{
<GridViewName>.SelectRow(rowHandle);------------------------------------ -----5
}
}
Clear all previous selection.
Loop through rows needed to be selected in your grid.
Get their row handles from grid (Note here grid is already updated with new rows)
Checking if the row handle is valid or not.
When valid row handle then select it.
Where itemList is list of rows to be selected in the grid view.
Try This:
datagridview.Rows[currentRow].Cells[0];
You can use the Select method if you have a datasource:
http://msdn.microsoft.com/en-us/library/b51xae2y%28v=vs.71%29.aspx
Or use linq if you have objects in you datasource
Try this:
DataGridViewRow row = dataGridView1.Rows[index row you want];
dataGridView1.CurrentRow = row;
Hope this help!

Categories

Resources