sometimes I want to hide buttons in a DataGridViewButtonColumn
Asked Answered
G

9

13

I have a DataGridView which was the subject of a previous question (link). But sometimes the Button is null. This is fine. But if it is null, is there any way I can optionally remove/add (show/hide?) buttons to the DataGridViewButtonColumn of Buttons

like this:

+------------+------------+
| MyText     | MyButton   |
+------------+------------+
| "do this"  | (Yes)      |
| "do that"  | (Yes)      |
| FYI 'blah' |            | <---- this is where I optionally want no button
| "do other" | (Yes)      |
+------------+------------+

this is what I have tried so far (based on this example)

private void grdVerdict_CellFormat(object sender, DataGridViewCellFormattingEventArgs e)
{
   if (e.ColumnIndex == grdChoice.Columns["yesbutton"].Index)
   {
       if (grdVerdict[e.ColumnIndex, e.RowIndex].Value == null)
       {
            //grdVerdict[e.ColumnIndex, e.RowIndex].Visible = false; //<-says 'it is read only'
            //grdVerdict[e.ColumnIndex, e.RowIndex].Value = new DataGridTextBox(); //<- draws 'mad red cross' over whole grid
            //((Button)grdVerdict[e.ColumnIndex, e.RowIndex]).Hide; //<- won't work
       }
       else
       {
          e.Value = ((Button)grdChoice[e.ColumnIndex, e.RowIndex].Value).Text;
       }
   }
}
Gyn answered 8/8, 2014 at 9:53 Comment(3)
What should be there in place of button?Dyewood
just a blank nothing.. no button at allGyn
Keep it simple - set it to null and ignore its being clicked..Gehring
F
15

I had the same "problem" today. I also wanted to hide buttons of certain rows. After playing around with it for a while, I discovered a very simple and nice solution, that doesn't require any overloaded paint()-functions or similar stuff:

Just assign a different DataGridViewCellStyle to those cells.
The key is, that you set the padding property of this new style to a value that shifts the whole button out of the visible area of the cell.
That's it! :-)

Sample:

System::Windows::Forms::DataGridViewCellStyle^  dataGridViewCellStyle2 = (gcnew System::Windows::Forms::DataGridViewCellStyle());
dataGridViewCellStyle2->Padding = System::Windows::Forms::Padding(25, 0, 0, 0);

dgv1->Rows[0]->Cells[0]->Style = dataGridViewCellStyle2;
// The width of column 0 is 22.
// Instead of fixed 25, you could use `columnwidth + 1` also.
Fifteen answered 12/3, 2015 at 12:55 Comment(6)
Sir, you are a genius! Worked like a charm :)Basilbasilar
I recommend 'Column.Width + 1000' otherwise the button can become visible if the user maximize the formOlnay
Unnecessary complications require ingenious solutions. Brilliant!Billhead
Just tried it and it works! @Olnay A lot of screen widths are > 1000 pixels nowadays. That said, perhaps even better would be to use top or bottom padding. If your grid has non-resizable rows, the button would never become visible this way. And needless to say, you will probably want to define the cell style in a class member variable, so that you need only to set it up once.Sly
Eventually worked for me, but I had add vertical padding like @Sly suggested. I also had to edit the DataGridViewColumn in the Designer and set Resizable=False and set the AutoSizeRowsMode=None for the DataGridView since my columns needed to be resizable.Selfoperating
I refactored my datagridview to use a bindinglist backed datasource and ran into this problem again. When using a datasource, I noticed that no individual style changes were taking effect so it seemed that some event was reverting my style changes back to the column default style. Therefore, the second half of this solution was to add these changes to the DataGridView::CellFormatting event handler so they wouldn't be replaced with the defaults. See https://mcmap.net/q/904211/-cell-formatting-in-datagridview-on-databindingcompleteSelfoperating
M
4

Based on Tobias' answer I made a small static helper method to hide the contents of the cell by adjusting it's padding.

Be aware though that the button is still "clickable" in that if the user selects the cell and presses space it clicks the hidden button, so I check that the cell's value is not readonly before I process any clicks in my contentclick event

  public static void DataGridViewCellVisibility(DataGridViewCell cell, bool visible)
  {
        cell.Style = visible ?
              new DataGridViewCellStyle { Padding = new Padding(0, 0, 0, 0) } :
              new DataGridViewCellStyle { Padding = new Padding(cell.OwningColumn.Width, 0, 0, 0) };

        cell.ReadOnly = !visible;
  }
Mcgannon answered 30/11, 2015 at 2:58 Comment(1)
You could improve it by overloading the keydown event and ignore space when the button is not visible.Fifteen
T
4

Put the button to the right and ready

DataGridViewCellStyle  dataGridViewCellStyle2 = new DataGridViewCellStyle();
dataGridViewCellStyle2.Padding = new Padding(0, 0, 1000, 0);
row.Cells["name"].Style = dataGridViewCellStyle2;   
Threatt answered 30/7, 2019 at 1:48 Comment(0)
L
2

Padding didn't work for me. I think it is easier and cleaner to just make the cell an empty text cell. VB, but you get the idea:

Dim oEmptyTextCell As New DataGridViewTextBoxCell()
oEmptyTextCell.Value = String.Empty
oRow.Cells(i) = oEmptyTextCell
Lophophore answered 16/1, 2018 at 15:57 Comment(0)
G
2

As an improvement to Sriram's answer, I would suggest just overriding the cell painting event and only painting the background. I found that painting a textbox made it look a little odd.

void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.ColumnIndex == yourColumnIndex && String.IsNullOrEmpty((string)e.FormattedValue))
    {
        e.PaintBackground(e.ClipBounds, true);
        e.Handled = true;
    }
}
Gownsman answered 8/6, 2018 at 14:42 Comment(0)
V
1

You can disabled a DataGridViewButton with a little effort as suggested in this post: Disabling the button column in the datagridview

I preferred using a DataGridViewImageColumn and DataGridView.CellFormatting event to display different pictures as an image button could be enabled or not.

In this case, if button must be disabled you can display a blank image and do nothing on DataGridView.CellClick event.

Voltameter answered 8/8, 2014 at 10:2 Comment(3)
the (DataGridViewDisableButtonCell).Enabled property doesn't update until mouse over, so this is too sub optimal, sorryGyn
Try using a DataGridViewImageColumns as suggested in the answer.Voltameter
thanks for the suggestion, but it's not sufficient by way of explanationGyn
D
1

Handle custom painting and paint a textbox over there.

void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.ColumnIndex == yourColumnIndex && String.IsNullOrEmpty((string)e.FormattedValue))
    {
        Graphics g = e.Graphics;
        TextBoxRenderer.DrawTextBox(g, e.CellBounds,
            System.Windows.Forms.VisualStyles.TextBoxState.Normal);
        e.Handled = true;
    }
}
Dyewood answered 8/8, 2014 at 11:25 Comment(0)
E
0

I just put padding all sides to the cell height & width (whichever is larger.)

Errata answered 18/10, 2018 at 14:12 Comment(0)
U
-1

For a more simple solution it is possible to hide the column containing the button you want to hide.

For example: GridView1.Columns[0].Visible = false; (First column)

Just count which column you want to hide starting from 0.

Unhandsome answered 18/1, 2018 at 11:49 Comment(1)
I don't think this is an answer to the question. OP does not want to remove a complete column.Trephine

© 2022 - 2024 — McMap. All rights reserved.