如果行不可编辑,请在DataGridView列中更改图标编辑

时间:2015-02-20 03:21:32

标签: c# datagridview

我以编程方式在datagridview中创建了列。首先是编辑列,键列,值列,并且是可编辑的列(隐藏),如下面的代码所示:

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
    });
}

如果disabled_edit.png的值为false,我想显示isEditableColumn图标或空单元格。如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您可以使用在需要格式化单元格内容以进行显示时发生的DataGridView.CellFormatting事件。

VB.NET中的伪代码(对不起):

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