.net 在 Datagridview 中启用和禁用单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/629107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 12:17:56  来源:igfitidea点击:

Enabling and disabling a cell in a Datagridview

.netdatagridview

提问by Victor Ionescu

I am using a DataGridView control for displaying some data. I need to enable some data and disable some data dynamically based on some values in the grid.

我正在使用 DataGridView 控件来显示一些数据。我需要根据网格中的某些值动态启用某些数据并禁用某些数据。

Can anyone tell me how to do it?

谁能告诉我怎么做?

回答by Victor Ionescu

To "disable" a cell, it must be read-only and grayed out somehow. This function enables/disables a DataGridViewCell:

要“禁用”一个单元格,它必须是只读的并且以某种方式变灰。此函数启用/禁用 DataGridViewCell:

    /// <summary>
    /// Toggles the "enabled" status of a cell in a DataGridView. There is no native
    /// support for disabling a cell, hence the need for this method. The disabled state
    /// means that the cell is read-only and grayed out.
    /// </summary>
    /// <param name="dc">Cell to enable/disable</param>
    /// <param name="enabled">Whether the cell is enabled or disabled</param>
    private void enableCell(DataGridViewCell dc, bool enabled) {
        //toggle read-only state
        dc.ReadOnly = !enabled;
        if (enabled)
        {
            //restore cell style to the default value
            dc.Style.BackColor = dc.OwningColumn.DefaultCellStyle.BackColor;
            dc.Style.ForeColor = dc.OwningColumn.DefaultCellStyle.ForeColor;
        }
        else { 
            //gray out the cell
            dc.Style.BackColor = Color.LightGray;
            dc.Style.ForeColor = Color.DarkGray;
        }
    }

回答by Blorgbeard is out

You can set a particular row or cell to be read-only, so the user cannot change the value. Is that what you mean?

您可以将特定行或单元格设置为只读,因此用户无法更改该值。你是这个意思吗?

dataGridView1.Rows[0].ReadOnly = true;
dataGridView1.Rows[1].Cells[2].ReadOnly = true;

回答by Thamis

Step 1:

第1步:

type form load : -
For i = 0 to Datagridview.columns.count -1
   if i <> 1 then //restricted columns, 'i' is Your column index
    Datagridview.Columns(i).ReadOnly = True
   end if
Next

Step 2

第2步

type Cellbeginedit
Datagridview.BeginEdit(True)