Willy
Willy

Reputation: 1729

Change Icon Edit in DataGridView Column If The Row is not Editable

I created columns in datagridview programmatically. First is the edit column, key column, value column, and is editable column (hide) as shown in the code below:

private void InitGrid()
{
    DataGridViewImageColumn editColumn = new DataGridViewImageColumn();
    editColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
    editColumn.HeaderText = "";
    editColumn.Image = global::WindowsForms.Properties.Resources.edit;
    editColumn.Name = Global.ACTION_EDIT;
    editColumn.Width = 30;

    DataGridViewTextBoxColumn keyColumn = new DataGridViewTextBoxColumn();
    keyColumn.DataPropertyName = "Key";
    keyColumn.HeaderText = "Key";
    keyColumn.Name = "Key";

    DataGridViewTextBoxColumn valueColumn = new DataGridViewTextBoxColumn();
    valueColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
    valueColumn.DataPropertyName = "Value";
    valueColumn.HeaderText = "Value";
    valueColumn.Name = "Value";

    DataGridViewTextBoxColumn isEditableColumn = new DataGridViewTextBoxColumn();
    isEditableColumn.DataPropertyName = "IsEditable";
    isEditableColumn.HeaderText = "IsEditable";
    isEditableColumn.Name = "IsEditable";
    isEditableColumn.Visible = false;

    dgvConfiguration.Columns.AddRange(new DataGridViewColumn[] { editColumn, 
        keyColumn, valueColumn, isEditableColumn
    });
}

I would like to display disabled_edit.png icon or empty cell if the value of isEditableColumn is false. How to solve this problem?

Upvotes: 0

Views: 1169

Answers (1)

tezzo
tezzo

Reputation: 11115

You can use DataGridView.CellFormatting event that occurs when the contents of a cell need to be formatted for display.

Pseudocode in VB.NET (sorry):

If e.ColumnIndex = -1 Or e.RowIndex = -1 Then Exit Sub

With Me.YourDataGridView
    If .Columns(e.ColumnIndex).Name = "YourDataGridViewImageColumnName" Then
        If .Rows(e.RowIndex).Cells("IsEditable").Value Then
            e.Value = <code to get edit.png>
        Else
            e.Value = <code to get disable_edit.png>
        End If
    End If
End With

Upvotes: 1

Related Questions