DataGridViewCheckBoxCell is not getting checked - c#

DataGridViewCheckBoxCell is not getting checked. I have inserted the first column like this
DataGridView1.Columns.Insert(0, new DataGridViewCheckBoxColumn { Name = "Print" });
This is not working
DataGridView1.Rows[0].Cells[0].Value = true;
Neither this is working
DataGridView1.Rows[0].Cells[0].Value = cell.TrueValue;
What could be the reason it is not getting checked?

I was having issues with this myself. I was using the following code, and I couldnt figure out why it wasn't working right all of the time.
(Note that my code is in VB, but I think the same concept would apply to other .NET languages)
Dim check As DataGridViewCheckBoxCell = DataGridView1.Rows(i).Cells("columnNameHere")
If check.Value = check.TrueValue Then
'do stuff
End If
I then realized that it was because the underlying value of the cell isnt changed until it loses focus. I think DGVs always behave like this, but it can be easy to forget.
My solution was to simply add a little bit of code to the data grid views on click event handler. When the user clicks the checkbox, all it does is shift the focus elsewhere. I shifted the focus to a label so that it doesnt have any unintended consequences. (Ex: if you shift it to a button the user might be surprised when they press enter and a random button activates.) Depending on what else is in your DGV, you may want to check the column index of the event so that you are only doing this for the checkbox columns. All of the other columns in my DGV are read only anyways, so it didnt matter in my case.
Private Sub DataGridView1_CellContentClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Label1.Focus()
End Sub
If the code in question was contained in a button, the focus would already be shifted away from the DGV to the button, so this wouldn't be an issue. In my case, the code was activated by a timer - meaning that the DGV cell in question wouldn't necissarily lose focus before the timer fired.

I don't know why it is not working for you, but you can try following method instead.
dataGridView1.Rows[0].SetValues(true);
This will only check the first item. When you want to set values for more cells, just use more parameters.
var values = new bool[] { true, false, true };
dataGridView1.Rows[0].SetValues(values);
This will check the first and the third cell, but the second cell will remain unchecked.

your first line of code actually worked for me:
DataGridView1.Rows[0].Cells[0].Value = true;
checked the first line. the second line isn't working because there is no meaning to cell.TrueValue, and a cell's property TrueValue is not a const of a checked check box
let me just add that the way you address your DataGridView's properties is not very safe and can cause exceptions

Is your datagridview Edit Mode property is set to Edit Programmatically ?
I was having the same issue, So I changed my datagridview Edit Mode property to Edit on Enter. Now it's working fine for me.
Please set your datagridview Edit Mode to Edit on Enter.
If you want to make other (Non Checkbox) columns read only use DataDridView1.Column("Column Name Here Or Index").Readonly = True to made them read only.
Sorry For Late, But other searchers can get some helps from this answer.

If you just want to add new checkbox column and want to check`uncheckcheckboxes in column you need to addTrueValueandFalseValuefor yourCheckBoxColumn`. Go to the Edit Columns dialog and set TrueValue and FalseValue attributes for your column.
Thanks.

Related

How can the datagridview directly after assign a value in code?

I have a WinForms application and i use datagridview in form. The DataGridView have many checkbox columns and the cells can be selected and processed by code.
So it's possible to check/uncheck all cells or copy to/insert from clipboard. This works fine except the last selected checkbox. 1st value is not shown as long as the cell is selected.
I have tried to set SuspendLayout, Refresh, Update and then ResumeLayout. But any one of them does not work for me.
private void SetCheckBoxCells(bool value)
{
myDataGridView.SuspendLayout();
foreach (var cell in myDataGridView.SelectedCells)
{
(cell as DataGridViewCheckBoxCell).Value = value;
}
myDataGridView.Refresh();
myDataGridView.Update();
myDataGridView.ResumeLayout();
}
I expect that all cells are visually set/unset after click on the menu entry, but the last one is visually set after deselect the cells.
The issue is almost certainly not caused by the Refresh/Update. If that was a problem, you'd see a correct value after first manual edit in other cell. You can also check the value, i.e. simply:
MSgbox(myDataGridView.Rows[1].Cells[0].Value.ToString);
Obviously, with correct indexes. I'm sure you'll get what you see, though.
foreach in SelectedCells should be pretty robust and does not suffer from index error, so I would double check, whether a CellEdit state, or CurrentCell focus or some event does not interfere with the first cell, preventing it to be updated.
Perhaps try setting current cell to something outside the selected range:
myDataGridView.CurrentCell = myDataGridView.Rows[1].Cells[0];
// some other cell not included in selection
What the integers (x1 to y2) are doing there? They're not employed. Just left from testing? Try to address the troublesome cell directly (just for debugging), simply like that:
myDataGridView.Rows[1].Cells[0].value = True
Obviously with correct indexes. Perhaps it will tell a bit more about the problem.

C# DataGridView 1st CheckBox Cell redrawing as unchecked. Why?

Issue Solved - Posted for reference.
Hi, I have a strange error occurring.
I have a DataGridView that I am using to store a list of records, these records are being updated from a source by a BackgroundWorker. There is a CheckBox Column that allows the user to select records from the DataGridView for processing.
When I check the CheckBox the first row(and only the first row), the checkbox does not seem to refresh correctly and displays as unchecked. The checkbox is still being treated as checked and the logic tied to it is working correctly. This is a cosmetic issue that may confuse users.
any other CheckBox in the DataGridView draws correctly at all times.
Clicking anywhere on the DataGridView causes the CheckBox state to redraw correctly.
It seems like a redrawing issue, but I am having trouble tracking down why it is drawing like this.
Some details of relevance.
It is necessary for me to reload the dataset with each refresh.
I have set the cell highlight colors to be the same as the non-highlighted ones.
I have a routine that checks the Checked state of the CheckBoxes, records the records that have been selected and rechecks the checkboxes when the dataset has been replaced. -This is working correctly
See the following code.
private void BgwDocketList_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
var checkedRows = from DataGridViewRow r in Dgv_Batch.Rows
where Convert.ToBoolean(r.Cells[0].Value) == true
select r;
List<int> L = new List<int>();
foreach (DataGridViewRow x in checkedRows)
{
L.Add((int)x.Cells[1].Value);
}
Dgv_Batch.DataSource =e.Result;
foreach (DataGridViewRow v in Dgv_Batch.Rows)
{
if (L.Count(x=>x==(int)v.Cells[1].Value)>0)
{
v.Cells[0].Value = true;
}
}
}
Have tried changing the selected cell programmatically
I have tried setting focus to the DataGridView in an attempt to programmatically recreate the effect of clicking on the control. This does not redraw the checkbox. only a mouse click seems to do this.
...Ok...
While Writing this I have managed to solve the problem. I guess it helps to write down the steps to ensure they are checked out.
The issue was that after updating the checkboxes I needed to use
DataGridView.EndEdit()
I would have expected that routine to have worked on the last record last as opposed to the first. I guess this relates back to the DataGridView.DataGridViewSelectedRowCollection containing a reversed index.
I have posted this Question anyway in the hope that It may help someone with the same issue.
Utilize
DataGridView.EndEdit();
This will solve the problem.

Programmatically setting a datagridview cell value, but dataAdapter.Update() does not update the DB [duplicate]

I am using the DataGridView Control for reading and writing an XML file through XML Serialization.
I have an issue as explained below:
I read an XML file and populate DataGridView controls with the deserialized object.
I update all the values on the DataGridView on the cell.
I choose the File Save As option without losing focus on the last cell.
After this, the value of the particular cell is not updated. If I intentionally shift focus away (say I click on another cell on the same grid) the value is updated.
Can anyone suggest any solution for this?
The best way (though quick and dirty) is to assign the currentCell value to Nothing.
For example, in the save method, do:
dgvMyGrid.CurrentCell = Nothing
and then proceed further.
It's because the edited cell value is not committed to the DataSource until it's validated, which happens when the cell lose focus. If you want to commit the modifications immediately, you can handle the CurrentCellDirtyStateChanged event, and call the CommitEdit method in the handler :
void dataGridView1_CurrentCellDirtyStateChanged(object sender,
EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
If I understand you correctly, a cell is in editing mode and you're trying to programmatically stop editing and pass the value to the underlying datasource?
I'm using a somewhat "dirty" approach to do that in one of my applications:
if (dataGridView1.CurrentCell.IsInEditMode)
{
int y = dataGridView1.CurrentCellAddress.Y;
int x = dataGridView1.CurrentCellAddress.X;
if (y > 0)
dataGridView1.CurrentCell = dataGridView1.Rows[y - 1].Cells[x];
else
dataGridView1.CurrentCell = dataGridView1.Rows[y + 1].Cells[x];
dataGridView1.CurrentCell = dataGridView1.Rows[y].Cells[x];
}
That piece of code first checks whether the current cell is in edit mode. Then it changes the current cell programmatically (either to the previous row or the next row in case we're in the first row). After that, it restores the current cell selection.
You would call this code in your "File Save As" handler.
I had the same situation and I was even using accelerator keys for save button for saving the grid values. When I click on Save button focus lost from DGV and hence cell value is committed, but when I use accelerator keys focus doesn't lost from DGV hence no committing of the cell value.
After looking at the Amit Karmakar answer out of curiosity I tried that answer and it worked. To find out more details I went into debugging of the DGV and found that it is really same thing as commitedit which somehow doesn't work if you use it in the save button click.
When we set CurrentCell of DGV to null, before setting it to null DGV first gets the edited value and pushes it in to cell value and then sets CurrentCell REFERENCE to null. Here it doesn't mean that it is setting underlying DGV cell to null. Hence this works perfectly for the above problem.
Note: This solution may not work perfectly when you have validating events for the cell and if user enters invalid data which will fail validation. In this case setting current cell to null also fails as it cannot push the value to cell.
I gave this explanation as I've raised question on Amit Karmakar answer asking how can it be possible. I thought it may help some other, so dropped this explanation as answer.
OK, this is UGLY but it works to get the FINAL CHANGES from the grid WITHOUT having to move to another row:
With DataGridView1
.DataSource = Nothing
.DataSource = gridDataTable
Dim changedFoo As DataTable = gridDataTable.GetChanges
End With
However I still like the answer from Amit Karmakar the best.
I've added the 'DataGridView1.CurrentCell = Nothing' to the DataGridView1 LostFocus event.
You can get the value of a cell which is not yet committed using the EditedFormattedValue property for the current cell, as below
dataGridView1.CurrentCell.EditedFormattedValue

Check all check boxes in DataGridView at the same time

GOAL: Being able to check all check boxes upon firing an event handler.
CURRENTLY: Event handler fires as it should. I have a foreach loop that goes through each row and checks the check box in that row.
PROBLEM: If I were to select a row prior to 'Check All', all check boxes are checked EXCEPT for the check box in the row that was selected/highlighted. If I click somewhere else outside of the check box area after that, the check box then checks itself.
QUESTION: How do I make it so that ALL check boxes are checked at the SAME TIME regardless of which row is selected or not?
CODE:
foreach (DataGridViewRow row in mTargets.Rows)
{
//row.Cells[(int) menuItem.Tag].Value is the check box
//mDeselect is the boolean that I want to set
row.Cells[(int) menuItem.Tag].Value = !mDeselect;
}
ATTEMPTS: I've tried clearing selections and suspending/resuming layout. I've also tried to research to see if others have had the same problem, but it's a topic that is hard to find.
Any elegant suggestions or references to solutions that could help is greatly appreciated! Thank you!
UPDATED WITH ELEGANT SOLUTION & EXPLANATION: The reason why this side effect happens is due to the fact that the DataGridViewCheckBoxCell thinks it's still in edit mode whenever you happen to select the cell (or as it seems, that you're selecting that row). To solve the problem, here is the code that I put before my foreach loop that helped me fix the issue:
if (mTargets.IsCurrentCellInEditMode)
{
mTargets.EndEdit();
}
The reason why this side effect happens is due to the fact that the DataGridViewCheckBoxCell thinks it's still in edit mode whenever you happen to select the cell (or as it seems, that you're selecting that row). To solve the problem, here is the code that I put before my foreach loop that helped me fix the issue:
if (mTargets.IsCurrentCellInEditMode)
{
mTargets.EndEdit();
}
I have had this problem before too. It is not that it does not set that value, it just does not paint correctly. The way i fixed it (by far not idea, but works) is to set the check box values, then change the selected row to another row, then change it back.

Unchecking the user checked checkbox in the datagridview cell

I have a column in my DataGridView which has the DataGridViewCheckBoxColumn as column template. When user checks the checkbox, I need to uncheck it programmatically if it fails some conditions. I have done this, but this uncheck logic only takes effect after I change the focus from the cell manually. I tried changing the focus programmatically but didn't work. Is there any solution for this?
I found the answer with little code changes. I used the cancel edit function of datagridview. For checkbox value change to be fired previously i was using this code inside
CurrentCellDirtyStateChanged event.
CommitEdit(DataGridViewDataErrorContexts.Commit)
Now i changed it to.
CommitEdit(DataGridViewDataErrorContexts.CurrentCellChange)
And called the
CancelEdit()
to roll back the changes.
Just set value of your DataGridViewCell.Value property to false (or true):
((DataGridViewCheckBoxCell)row.Cells[CheckBoxColumn.Index]).value = false;
Recently I had similar problem. Setting Cell Value on false or working with TrueValue and FalseValue (for DataGridViewCheckBoxCell) failed in my case.
Finally i manage to achieve what I wanted (unchecking if some condition fails) with simple DataGridView method:
dataGridView1.CancelEdit()
Hope it helps.

Categories