如何:禁用 Windows 窗体 DataGridView 控件的按钮列中的按钮

C# WinForm控件开发指南:从基础控件到实战应用 C#桌面开发中,控件是构建用户界面的核心组件,它们作为程序与用户交互的桥梁,负责数据的输入、展示和操作响应。控件的原理基于事件驱动模型,通过属性、事件和布局三大要素协同工作,实现丰富的交互逻辑。掌握控件的使用不仅能提升开发效率,还能构建出专业、易用的应用程序界面,在企业管理软件、数据录入系统、工具软件等场景中广泛应用。本文聚焦WinForm控件的核心概念,深入解析常用控件的特性与实战技巧,涵盖按钮、文本框、数据网格等关键组件,帮助开发者从基础入门到灵活运用,快速构建功能完善的桌面应用。 阅读详情

 

中国 - 简体中文  Dropdown Arrow
欢迎您 登录
 如何:禁用 Windows 窗体 DataGridView 控件的按钮列中的按钮
Windows 窗体编程
如何:禁用 Windows 窗体 DataGridView 控件的按钮列中的按钮

 

DataGridView 控件包括 DataGridViewButtonCell 类,该类用于显示具有类似按钮的用户界面 (UI) 的单元格。但 DataGridViewButtonCell 不提供禁用由单元格显示的按钮外观的方式。

下面的代码示例演示如何自定义 DataGridViewButtonCell 类来显示可以显示为禁用的按钮。本示例定义一个新的单元格类型 DataGridViewDisableButtonCell,它由 DataGridViewButtonCell 派生。此单元格类型提供一个新的 Enabled 属性,可以将该属性设置为 false 来在单元格中绘制禁用的按钮。本示例还定义一个新的列类型 DataGridViewDisableButtonColumn,它显示 DataGridViewDisableButtonCell 对象。为了演示此新单元格类型和列类型,父 DataGridView 中的每个 DataGridViewCheckBoxCell 的当前值确定同一行中 DataGridViewDisableButtonCellEnabled 属性是 true 还是 false

Note注意

当从 DataGridViewCellDataGridViewColumn 派生并向派生类添加新属性时,请确保重写 Clone 方法以便在克隆操作期间复制新属性。还应调用基类的 Clone 方法,以便将基类的属性复制到新的单元格或列中。

示例

Visual Basic
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Imports System.Windows.Forms.VisualStyles

Class Form1
    Inherits Form
    Private WithEvents dataGridView1 As New DataGridView()

    <STAThread()> _
    Public Shared Sub Main()
        Application.EnableVisualStyles()
        Application.Run(New Form1())
    End Sub

    Public Sub New()
        Me.AutoSize = True
    End Sub

    Public Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _
        Handles Me.Load

        Dim column0 As New DataGridViewCheckBoxColumn()
        Dim column1 As New DataGridViewDisableButtonColumn()
        column0.Name = "CheckBoxes"
        column1.Name = "Buttons"
        dataGridView1.Columns.Add(column0)
        dataGridView1.Columns.Add(column1)

        dataGridView1.RowCount = 8
        dataGridView1.AutoSize = True
        dataGridView1.AllowUserToAddRows = False
        dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = _
            DataGridViewContentAlignment.MiddleCenter

        ' Set the text for each button.
        Dim i As Integer
        For i = 0 To dataGridView1.RowCount - 1
            dataGridView1.Rows(i).Cells("Buttons").Value = _
                "Button " + i.ToString()
        Next i

        Me.Controls.Add(dataGridView1)

    End Sub

    ' This event handler manually raises the CellValueChanged event
    ' by calling the CommitEdit method.
    Sub dataGridView1_CurrentCellDirtyStateChanged( _
        ByVal sender As Object, ByVal e As EventArgs) _
        Handles dataGridView1.CurrentCellDirtyStateChanged

        If dataGridView1.IsCurrentCellDirty Then
            dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
        End If
    End Sub

    ' If a check box cell is clicked, this event handler disables  
    ' or enables the button in the same row as the clicked cell.
    Public Sub dataGridView1_CellValueChanged(ByVal sender As Object, _
        ByVal e As DataGridViewCellEventArgs) _
        Handles dataGridView1.CellValueChanged

        If dataGridView1.Columns(e.ColumnIndex).Name = "CheckBoxes" Then
            Dim buttonCell As DataGridViewDisableButtonCell = _
                CType(dataGridView1.Rows(e.RowIndex).Cells("Buttons"), _
                DataGridViewDisableButtonCell)

            Dim checkCell As DataGridViewCheckBoxCell = _
                CType(dataGridView1.Rows(e.RowIndex).Cells("CheckBoxes"), _
                DataGridViewCheckBoxCell)
            buttonCell.Enabled = Not CType(checkCell.Value, [Boolean])

            dataGridView1.Invalidate()
        End If
    End Sub

    ' If the user clicks on an enabled button cell, this event handler  
    ' reports that the button is enabled.
    Sub dataGridView1_CellClick(ByVal sender As Object, _
        ByVal e As DataGridViewCellEventArgs) _
        Handles dataGridView1.CellClick

        If dataGridView1.Columns(e.ColumnIndex).Name = "Buttons" Then
            Dim buttonCell As DataGridViewDisableButtonCell = _
                CType(dataGridView1.Rows(e.RowIndex).Cells("Buttons"), _
                DataGridViewDisableButtonCell)

            If buttonCell.Enabled Then
                MsgBox(dataGridView1.Rows(e.RowIndex). _
                    Cells(e.ColumnIndex).Value.ToString() + _
                    " is enabled")
            End If
        End If
    End Sub

End Class

Public Class DataGridViewDisableButtonColumn
    Inherits DataGridViewButtonColumn

    Public Sub New()
        Me.CellTemplate = New DataGridViewDisableButtonCell()
    End Sub
End Class

Public Class DataGridViewDisableButtonCell
    Inherits DataGridViewButtonCell

    Private enabledValue As Boolean
    Public Property Enabled() As Boolean
        Get
            Return enabledValue
        End Get
        Set(ByVal value As Boolean)
            enabledValue = value
        End Set
    End Property

    ' Override the Clone method so that the Enabled property is copied.
    Public Overrides Function Clone() As Object
        Dim Cell As DataGridViewDisableButtonCell = _
            CType(MyBase.Clone(), DataGridViewDisableButtonCell)
        Cell.Enabled = Me.Enabled
        Return Cell
    End Function

    ' By default, enable the button cell.
    Public Sub New()
        Me.enabledValue = True
    End Sub

    Protected Overrides Sub Paint(ByVal graphics As Graphics, _
        ByVal clipBounds As Rectangle, ByVal cellBounds As Rectangle, _
        ByVal rowIndex As Integer, _
        ByVal elementState As DataGridViewElementStates, _
        ByVal value As Object, ByVal formattedValue As Object, _
        ByVal errorText As String, _
        ByVal cellStyle As DataGridViewCellStyle, _
        ByVal advancedBorderStyle As DataGridViewAdvancedBorderStyle, _
        ByVal paintParts As DataGridViewPaintParts)

        ' The button cell is disabled, so paint the border,  
        ' background, and disabled button for the cell.
        If Not Me.enabledValue Then

            ' Draw the background of the cell, if specified.
            If (paintParts And DataGridViewPaintParts.Background) = _
                DataGridViewPaintParts.Background Then

                Dim cellBackground As New SolidBrush(cellStyle.BackColor)
                graphics.FillRectangle(cellBackground, cellBounds)
                cellBackground.Dispose()
            End If

            ' Draw the cell borders, if specified.
            If (paintParts And DataGridViewPaintParts.Border) = _
                DataGridViewPaintParts.Border Then

                PaintBorder(graphics, clipBounds, cellBounds, cellStyle, _
                    advancedBorderStyle)
            End If

            ' Calculate the area in which to draw the button.
            Dim buttonArea As Rectangle = cellBounds
            Dim buttonAdjustment As Rectangle = _
                Me.BorderWidths(advancedBorderStyle)
            buttonArea.X += buttonAdjustment.X
            buttonArea.Y += buttonAdjustment.Y
            buttonArea.Height -= buttonAdjustment.Height
            buttonArea.Width -= buttonAdjustment.Width

            ' Draw the disabled button.                
            ButtonRenderer.DrawButton(graphics, buttonArea, _
                PushButtonState.Disabled)

            ' Draw the disabled button text. 
            If TypeOf Me.FormattedValue Is String Then
                TextRenderer.DrawText(graphics, CStr(Me.FormattedValue), _
                    Me.DataGridView.Font, buttonArea, SystemColors.GrayText)
            End If

        Else
            ' The button cell is enabled, so let the base class 
            ' handle the painting.
            MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, _
                elementState, value, formattedValue, errorText, _
                cellStyle, advancedBorderStyle, paintParts)
        End If
    End Sub

End Class
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;

class Form1 : Form
{
    private DataGridView dataGridView1 = new DataGridView();

    [STAThread]
    public static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new Form1());
    }

    public Form1()
    {
        this.AutoSize = true;
        this.Load += new EventHandler(Form1_Load);
    }

    public void Form1_Load(object sender, EventArgs e)
    {
        DataGridViewCheckBoxColumn column0 =
            new DataGridViewCheckBoxColumn();
        DataGridViewDisableButtonColumn column1 =
            new DataGridViewDisableButtonColumn();
        column0.Name = "CheckBoxes";
        column1.Name = "Buttons";
        dataGridView1.Columns.Add(column0);
        dataGridView1.Columns.Add(column1);
        dataGridView1.RowCount = 8;
        dataGridView1.AutoSize = true;
        dataGridView1.AllowUserToAddRows = false;
        dataGridView1.ColumnHeadersDefaultCellStyle.Alignment =
            DataGridViewContentAlignment.MiddleCenter;

        // Set the text for each button.
        for (int i = 0; i < dataGridView1.RowCount; i++)
        {
            dataGridView1.Rows[i].Cells["Buttons"].Value =
                "Button " + i.ToString();
        }

        dataGridView1.CellValueChanged +=
            new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
        dataGridView1.CurrentCellDirtyStateChanged +=
            new EventHandler(dataGridView1_CurrentCellDirtyStateChanged);
        dataGridView1.CellClick +=
            new DataGridViewCellEventHandler(dataGridView1_CellClick);

        this.Controls.Add(dataGridView1);
    }

    // This event handler manually raises the CellValueChanged event
    // by calling the CommitEdit method.
    void dataGridView1_CurrentCellDirtyStateChanged(object sender,
        EventArgs e)
    {
        if (dataGridView1.IsCurrentCellDirty)
        {
            dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }
    }

    // If a check box cell is clicked, this event handler disables  
    // or enables the button in the same row as the clicked cell.
    public void dataGridView1_CellValueChanged(object sender,
        DataGridViewCellEventArgs e)
    {
        if (dataGridView1.Columns[e.ColumnIndex].Name == "CheckBoxes")
        {
            DataGridViewDisableButtonCell buttonCell =
                (DataGridViewDisableButtonCell)dataGridView1.
                Rows[e.RowIndex].Cells["Buttons"];

            DataGridViewCheckBoxCell checkCell =
                (DataGridViewCheckBoxCell)dataGridView1.
                Rows[e.RowIndex].Cells["CheckBoxes"];
            buttonCell.Enabled = !(Boolean)checkCell.Value;

            dataGridView1.Invalidate();
        }
    }

    // If the user clicks on an enabled button cell, this event handler  
    // reports that the button is enabled.
    void dataGridView1_CellClick(object sender,
        DataGridViewCellEventArgs e)
    {
        if (dataGridView1.Columns[e.ColumnIndex].Name == "Buttons")
        {
            DataGridViewDisableButtonCell buttonCell =
                (DataGridViewDisableButtonCell)dataGridView1.
                Rows[e.RowIndex].Cells["Buttons"];

            if (buttonCell.Enabled)
            {
                MessageBox.Show(dataGridView1.Rows[e.RowIndex].
                    Cells[e.ColumnIndex].Value.ToString() +
                    " is enabled");
            }
        }
    }
}

public class DataGridViewDisableButtonColumn : DataGridViewButtonColumn
{
    public DataGridViewDisableButtonColumn()
    {
        this.CellTemplate = new DataGridViewDisableButtonCell();
    }
}

public class DataGridViewDisableButtonCell : DataGridViewButtonCell
{
    private bool enabledValue;
    public bool Enabled
    {
        get
        {
            return enabledValue;
        }
        set
        {
            enabledValue = value;
        }
    }

    // Override the Clone method so that the Enabled property is copied.
    public override object Clone()
    {
        DataGridViewDisableButtonCell cell =
            (DataGridViewDisableButtonCell)base.Clone();
        cell.Enabled = this.Enabled;
        return cell;
    }

    // By default, enable the button cell.
    public DataGridViewDisableButtonCell()
    {
        this.enabledValue = true;
    }

    protected override void Paint(Graphics graphics,
        Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
        DataGridViewElementStates elementState, object value,
        object formattedValue, string errorText,
        DataGridViewCellStyle cellStyle,
        DataGridViewAdvancedBorderStyle advancedBorderStyle,
        DataGridViewPaintParts paintParts)
    {
        // The button cell is disabled, so paint the border,  
        // background, and disabled button for the cell.
        if (!this.enabledValue)
        {
            // Draw the cell background, if specified.
            if ((paintParts & DataGridViewPaintParts.Background) ==
                DataGridViewPaintParts.Background)
            {
                SolidBrush cellBackground =
                    new SolidBrush(cellStyle.BackColor);
                graphics.FillRectangle(cellBackground, cellBounds);
                cellBackground.Dispose();
            }

            // Draw the cell borders, if specified.
            if ((paintParts & DataGridViewPaintParts.Border) ==
                DataGridViewPaintParts.Border)
            {
                PaintBorder(graphics, clipBounds, cellBounds, cellStyle,
                    advancedBorderStyle);
            }

            // Calculate the area in which to draw the button.
            Rectangle buttonArea = cellBounds;
            Rectangle buttonAdjustment =
                this.BorderWidths(advancedBorderStyle);
            buttonArea.X += buttonAdjustment.X;
            buttonArea.Y += buttonAdjustment.Y;
            buttonArea.Height -= buttonAdjustment.Height;
            buttonArea.Width -= buttonAdjustment.Width;

            // Draw the disabled button.                
            ButtonRenderer.DrawButton(graphics, buttonArea,
                PushButtonState.Disabled);

            // Draw the disabled button text. 
            if (this.FormattedValue is String) 
            {
                TextRenderer.DrawText(graphics,
                    (string)this.FormattedValue,
                    this.DataGridView.Font,
                    buttonArea, SystemColors.GrayText);
            }
        }
        else
        {
            // The button cell is enabled, so let the base class 
            // handle the painting.
            base.Paint(graphics, clipBounds, cellBounds, rowIndex,
                elementState, value, formattedValue, errorText,
                cellStyle, advancedBorderStyle, paintParts);
        }
    }
}

编译代码

此示例要求:

  • 对 System、System.Drawing、System.Windows.Forms 和 System.Windows.Forms.VisualStyles 程序集的引用。

有关从 Visual Basic 或 Visual C# 的命令行生成此示例的信息,请参见从命令行生成 (Visual Basic)命令行生成。也可以通过将代码粘贴到新项目,在 Visual Studio 中生成此示例。 有关更多信息,请参见 如何:使用 Visual Studio 编译和运行完整的 Windows 窗体代码示例.

请参见

计算机实战分享3:森林火灾预测分析可视化机器学习预测-完整数据代码-可直接运行 阅读详情

相关推荐

Qt入门教程【Core篇】singal and slot信号与槽

Qt中信号与槽singal and slot

小鱼酱的博客 2397

DataGridView禁用Button

实现DataGridView禁用Button(根据DataGridView某一行某一个单元格数据的状态控制其按钮的可用性)

C#如何禁用Windows 窗体 DataGridView 控件按钮中的按钮

代码示例演示如何自定义 DataGridViewButtonCell 类来显示可以显示为禁用按钮。 本示例定义一个新的单元格类型 DataGridViewDisableButtonCell,它由 DataGridViewButtonCell 派生。 此单元格类型提供一个新的 Enabled 属性,可以将该属性设置为 false 来在单元格中绘制禁用按钮。 本示例还定义一个新的类型 DataGridViewDisableButtonColumn,它显示 DataGridViewDisableButtonCell 对象。 为了演示此新单元格类型和类型,父 DataGridView 中的每个 DataGridViewCheckBoxCell 的当前值确定同一行中 DataGridViewDisableButtonCell 的 Enabled 属性是 true 还是 false。

[zt]C#DataGridView按钮禁用或不可点的方法(设置Enabled属性)

在项目中进行了使用,很好用。只需要对单元格进行强制转换后设置就可以了,如: ((DataGridViewDisableButtonColumn)dr.Cells["open"]).Enabled = false;

cqlray的专栏 1万+

C#禁止datagrid选中

用设备获取数据时用户选中了datagrid的行导致获取失败,所以禁用datagrid行的选中。

weixin_44957370的博客 968

C# 禁止 DataGridView 点击 标题 排序

C# 禁止 DataGridView 点击 标题 排序for (int i = 0; i {this.dataGridView3.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;}

longfengdie的专栏 5886

C# 如何:禁用 Windows 窗体 DataGridView 控件按钮中的按钮 Enable = false

usingSystem; usingSystem.Drawing; usingSystem.Windows.Forms; usingSystem.Windows.Forms.VisualStyles; classForm1:Form { privateDataGridViewdataGridView1=newDataGridView(); ...

weixin_30297281的博客 426

禁用 Windows 窗体 DataGridView 控件按钮中的按钮

//from :http://www.5acs.com/article.asp?id=472DataGridView 控件包括 DataGridViewButtonCell 类,该类用于显示具有类似按钮的用户界面 (UI) 的单元格。但 DataGridViewButtonCell 不提供禁用由单元格显示的按钮外观的方式。 下面的代码示例演示如何自定义 DataGridViewButt

changjiangzhibin的专栏 2265

C#禁用 Windows 窗体 DataGridView 控件按钮DataGridViewButtonColumn中的按钮

public class DataGridViewDisableButtonColumn : DataGridViewButtonColumn { public DataGridViewDisableButtonColumn() { CellTemplate = new DataGridViewDisableButtonCell();

ly418229459的专栏 2109

WinForm控件开发全解析:从基础添加到高级应用与性能优化

C#桌面开发中,控件是构建用户界面的核心组件,其本质是封装了特定功能的可视化对象,通过属性、方法和事件与用户交互。控件的生命周期管理、事件驱动机制以及布局原理构成了WinForm开发的基础。掌握控件的设计与运行时添加方式,能够显著提升开发效率与界面灵活性,这对于实现数据可视化、实时监控等应用场景至关重要。例如,通过PictureBox控件可以实现图像处理功能,而DataGridView则是数据展示的利器。本文深入探讨了控件的动态创建、事件绑定、性能优化等高级话题,并融入了双缓冲技术和异步UI更新等热词,帮

weixin_33849215的博客 446

初识Windows程序

一、B(rowser)/S(erver):浏览器/服务器` http:Hypertext Transfer Protocol 二、C(lient)/S(erver):客户端/服务端 TCP/IP;UDP/IP: IP :Internet Protocol TCP:Transfer Control Protocol UDP:User Datagram Protocol...

akuq88038的博客 361

DataGridView禁止一行被选中(行状态变化事件) C#

今天遇到一个需求,winform 表格(DataGridView)中需要让某些行不能被选中。如下图,默认所有行都能被选中。 表格中的行,可以通过多种方法选中,例如:单击一行可以选中,用ctrl、shift等快捷键也可以选中,单击左上角的一块也能全部选中. 解决的思路是通过控件的事件来做,根据常识,一行的选中或取消选中,肯定会触发一个选中或取消选中的事件,理论上可以在这个事件中将

小鹰信息技术服务部 1万+

CNN-LSTM卷积-长短期记忆网络数据回归预测python版本

CNN-LSTM卷积-长短期记忆网络数据回归预测python版本CNN-LSTM卷积-长短期记忆网络数据回归预测python版本CNN-LSTM卷积-长短期记忆网络数据回归预测python版本CNN-LSTM卷积-长短期记忆网络数据回归预测python版本CNN-LSTM卷积-长短期记忆网络数据回归预测python版本CNN-LSTM卷积-长短期记忆网络数据回归预测python版本CNN-LSTM卷积-长短期记忆网络数据回归预测python版本CNN-LSTM卷积-长短期记忆网络数据回归预测python版本CNN-LSTM卷积-长短期记忆网络数据回归预测python版本CNN-LSTM卷积-长短期记忆网络数据回归预测python版本CNN-LSTM卷积-长短期记忆网络数据回归预测python版本CNN-LSTM卷积-长短期记忆网络数据回归预测python版本CNN-LSTM卷积-长短期记忆网络数据回归预测python版本CNN-LSTM卷积-长短期记忆网络数据回归预测python版本CNN-LSTM卷积-长短期记忆网络数据回归预测python版本CNN-LSTM卷积-长短期记忆网络数据

上一篇: C#WinForm中按钮响应回车事件的简单方法
下一篇: 在DataGridView控件中加入ComboBox下拉列表框的实现
天下第一刀2020
博客等级 码龄24年 32粉丝 214原创
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值