I have a DataGridView and I want in my grid a column having some cells that display a button and some cells that do not contain the button. In order to solve this problem I've added a DataGridViewButtonColumn and I've written this method that I call to add the rows to my column:
private void AttachNewRow(bool validRow)
{
DataGridViewRow newRow = GetNewRow();
if (validRow)
{
newRow.Cells["Info"].Value = "Click me";
}
else
{
// Here I would like to hide the button in the cell
newRow.Cells["Info"].Value = null;
}
}
The problem is that when I set the cell value to null I receive an exception. How can I display some of these cells without the button inside? Thank you
Looks like the GetNewRow()
returns the Row
you are talking about already inserted in the DGV
.
If that function has the knowledge if the 'Info' Column
shall contain a Button
, it can pass it, maybe in the Tag
:
if (somecondiiotn) newRow.Columns["Info"].Tag = "Button";
Then you can write:
private void AttachNewRow()
{
DataGridViewRow newRow = GetNewRow();
if ( newRow.Cells["Info"].Tag == null ||
newRow.Cells["Info"].Tag != "Button") return;
//..
If otoh the code that calls AttachNewRow()
has the required knowledge, it could instead pass it on in a parameter:
private void AttachNewRow(bool infoButton)
If the knowlegde is available only later you can still change individual cells.
Update:
since you are now passing the condition into the method you can act accordingly.
I don't know why you get an exception in your code - I don't. But to really hide the Button
you should change the cell to be a 'normal' DataGridViewTextBoxCell
:
else
{
DataGridViewCell cell = new DataGridViewTextBoxCell();
newRow.Cells["Info"] = cell;