Skip to main content
 首页 » 编程设计

c#之Winform 数据绑定(bind)

2024年02月23日15Leo_wl

我需要启用/禁用 datagridview 的行列,这可以通过在绑定(bind)后循环所有行来轻松完成。 但是我想在数据绑定(bind)时这样做......有没有办法做到这一点?还有我如何启用/禁用行单元格?

dgvLayout.AutoGenerateColumns = false; 
dgvLayout.DataSource = list; 

在单元格中点击但不起作用

if ((dgvLayout.Rows[e.RowIndex].Cells["colControlText"].Value.ToString()) == "-Invalid-") 
{ 
    if (e.ColumnIndex == 2 || e.ColumnIndex == 5) 
    { 
        return; 
    } 
    else if (e.ColumnIndex == 1) 
    { 
        return; 
    } 
} 

请您参考如下方法:

您可以使用此解决方案来启用和禁用单元格

要“禁用”一个单元格,它必须是只读的并且以某种方式变灰。此函数启用/禁用 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; 
        } 
    }