DataGridViewButtonCell 类    
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
显示在 DataGridView 控件中使用的类似按钮的用户界面 (UI)。
public ref class DataGridViewButtonCell : System::Windows::Forms::DataGridViewCellpublic class DataGridViewButtonCell : System.Windows.Forms.DataGridViewCelltype DataGridViewButtonCell = class
    inherit DataGridViewCellPublic Class DataGridViewButtonCell
Inherits DataGridViewCell- 继承
示例
下面的代码示例演示如何使用 DataGridViewButtonColumn 对特定行执行操作。 使用单个 DataGridViewButtonCell 对象时,可以使用类似的代码。 在此示例中, DataGridView.CellClick 事件处理程序首先确定单击是否位于按钮单元格上,然后检索与该行关联的业务对象。 此示例是 How to: Access Objects in a Windows 窗体 DataGridViewComboBoxCell Drop-Down List 中提供的更大示例的一部分。
public class Form1 : Form
{
    private List<Employee> employees = new List<Employee>();
    private List<Task> tasks = new List<Task>();
    private Button reportButton = new Button();
    private DataGridView dataGridView1 = new DataGridView();
    [STAThread]
    public static void Main()
    {
        Application.Run(new Form1());
    }
    public Form1()
    {
        dataGridView1.Dock = DockStyle.Fill;
        dataGridView1.AutoSizeColumnsMode = 
            DataGridViewAutoSizeColumnsMode.AllCells;
        reportButton.Text = "Generate Report";
        reportButton.Dock = DockStyle.Top;
        reportButton.Click += new EventHandler(reportButton_Click);
        Controls.Add(dataGridView1);
        Controls.Add(reportButton);
        Load += new EventHandler(Form1_Load);
        Text = "DataGridViewComboBoxColumn Demo";
    }
    // Initializes the data source and populates the DataGridView control.
    private void Form1_Load(object sender, EventArgs e)
    {
        PopulateLists();
        dataGridView1.AutoGenerateColumns = false;
        dataGridView1.DataSource = tasks;
        AddColumns();
    }
    // Populates the employees and tasks lists. 
    private void PopulateLists()
    {
        employees.Add(new Employee("Harry"));
        employees.Add(new Employee("Sally"));
        employees.Add(new Employee("Roy"));
        employees.Add(new Employee("Pris"));
        tasks.Add(new Task(1, employees[1]));
        tasks.Add(new Task(2));
        tasks.Add(new Task(3, employees[2]));
        tasks.Add(new Task(4));
    }
    // Configures columns for the DataGridView control.
    private void AddColumns()
    {
        DataGridViewTextBoxColumn idColumn = 
            new DataGridViewTextBoxColumn();
        idColumn.Name = "Task";
        idColumn.DataPropertyName = "Id";
        idColumn.ReadOnly = true;
        DataGridViewComboBoxColumn assignedToColumn = 
            new DataGridViewComboBoxColumn();
        // Populate the combo box drop-down list with Employee objects. 
        foreach (Employee e in employees) assignedToColumn.Items.Add(e);
        // Add "unassigned" to the drop-down list and display it for 
        // empty AssignedTo values or when the user presses CTRL+0. 
        assignedToColumn.Items.Add("unassigned");
        assignedToColumn.DefaultCellStyle.NullValue = "unassigned";
        assignedToColumn.Name = "Assigned To";
        assignedToColumn.DataPropertyName = "AssignedTo";
        assignedToColumn.AutoComplete = true;
        assignedToColumn.DisplayMember = "Name";
        assignedToColumn.ValueMember = "Self";
        // Add a button column. 
        DataGridViewButtonColumn buttonColumn = 
            new DataGridViewButtonColumn();
        buttonColumn.HeaderText = "";
        buttonColumn.Name = "Status Request";
        buttonColumn.Text = "Request Status";
        buttonColumn.UseColumnTextForButtonValue = true;
        dataGridView1.Columns.Add(idColumn);
        dataGridView1.Columns.Add(assignedToColumn);
        dataGridView1.Columns.Add(buttonColumn);
        // Add a CellClick handler to handle clicks in the button column.
        dataGridView1.CellClick +=
            new DataGridViewCellEventHandler(dataGridView1_CellClick);
    }
    // Reports on task assignments. 
    private void reportButton_Click(object sender, EventArgs e)
    {
        StringBuilder report = new StringBuilder();
        foreach (Task t in tasks)
        {
            String assignment = 
                t.AssignedTo == null ? 
                "unassigned" : "assigned to " + t.AssignedTo.Name;
            report.AppendFormat("Task {0} is {1}.", t.Id, assignment);
            report.Append(Environment.NewLine);
        }
        MessageBox.Show(report.ToString(), "Task Assignments");
    }
    // Calls the Employee.RequestStatus method.
    void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        // Ignore clicks that are not on button cells. 
        if (e.RowIndex < 0 || e.ColumnIndex !=
            dataGridView1.Columns["Status Request"].Index) return;
        // Retrieve the task ID.
        Int32 taskID = (Int32)dataGridView1[0, e.RowIndex].Value;
        // Retrieve the Employee object from the "Assigned To" cell.
        Employee assignedTo = dataGridView1.Rows[e.RowIndex]
            .Cells["Assigned To"].Value as Employee;
        // Request status through the Employee object if present. 
        if (assignedTo != null)
        {
            assignedTo.RequestStatus(taskID);
        }
        else
        {
            MessageBox.Show(String.Format(
                "Task {0} is unassigned.", taskID), "Status Request");
        }
    }
}
Public Class Form1
    Inherits Form
    Private employees As New List(Of Employee)
    Private tasks As New List(Of Task)
    Private WithEvents reportButton As New Button
    Private WithEvents dataGridView1 As New DataGridView
    <STAThread()> _
    Public Sub Main()
        Application.Run(New Form1)
    End Sub
    Sub New()
        dataGridView1.Dock = DockStyle.Fill
        dataGridView1.AutoSizeColumnsMode = _
            DataGridViewAutoSizeColumnsMode.AllCells
        reportButton.Text = "Generate Report"
        reportButton.Dock = DockStyle.Top
        Controls.Add(dataGridView1)
        Controls.Add(reportButton)
        Text = "DataGridViewComboBoxColumn Demo"
    End Sub
    ' Initializes the data source and populates the DataGridView control.
    Private Sub Form1_Load(ByVal sender As Object, _
        ByVal e As EventArgs) Handles Me.Load
        PopulateLists()
        dataGridView1.AutoGenerateColumns = False
        dataGridView1.DataSource = tasks
        AddColumns()
    End Sub
    ' Populates the employees and tasks lists. 
    Private Sub PopulateLists()
        employees.Add(New Employee("Harry"))
        employees.Add(New Employee("Sally"))
        employees.Add(New Employee("Roy"))
        employees.Add(New Employee("Pris"))
        tasks.Add(New Task(1, employees(1)))
        tasks.Add(New Task(2))
        tasks.Add(New Task(3, employees(2)))
        tasks.Add(New Task(4))
    End Sub
    ' Configures columns for the DataGridView control.
    Private Sub AddColumns()
        Dim idColumn As New DataGridViewTextBoxColumn()
        idColumn.Name = "Task"
        idColumn.DataPropertyName = "Id"
        idColumn.ReadOnly = True
        Dim assignedToColumn As New DataGridViewComboBoxColumn()
        ' Populate the combo box drop-down list with Employee objects. 
        For Each e As Employee In employees
            assignedToColumn.Items.Add(e)
        Next
        ' Add "unassigned" to the drop-down list and display it for 
        ' empty AssignedTo values or when the user presses CTRL+0. 
        assignedToColumn.Items.Add("unassigned")
        assignedToColumn.DefaultCellStyle.NullValue = "unassigned"
        assignedToColumn.Name = "Assigned To"
        assignedToColumn.DataPropertyName = "AssignedTo"
        assignedToColumn.AutoComplete = True
        assignedToColumn.DisplayMember = "Name"
        assignedToColumn.ValueMember = "Self"
        ' Add a button column. 
        Dim buttonColumn As New DataGridViewButtonColumn()
        buttonColumn.HeaderText = ""
        buttonColumn.Name = "Status Request"
        buttonColumn.Text = "Request Status"
        buttonColumn.UseColumnTextForButtonValue = True
        dataGridView1.Columns.Add(idColumn)
        dataGridView1.Columns.Add(assignedToColumn)
        dataGridView1.Columns.Add(buttonColumn)
    End Sub
    ' Reports on task assignments. 
    Private Sub reportButton_Click(ByVal sender As Object, _
        ByVal e As EventArgs) Handles reportButton.Click
        Dim report As New StringBuilder()
        For Each t As Task In tasks
            Dim assignment As String
            If t.AssignedTo Is Nothing Then
                assignment = "unassigned"
            Else
                assignment = "assigned to " + t.AssignedTo.Name
            End If
            report.AppendFormat("Task {0} is {1}.", t.Id, assignment)
            report.Append(Environment.NewLine)
        Next
        MessageBox.Show(report.ToString(), "Task Assignments")
    End Sub
    ' Calls the Employee.RequestStatus method.
    Private Sub dataGridView1_CellClick(ByVal sender As Object, _
        ByVal e As DataGridViewCellEventArgs) _
        Handles dataGridView1.CellClick
        ' Ignore clicks that are not on button cells. 
        If e.RowIndex < 0 OrElse Not e.ColumnIndex = _
            dataGridView1.Columns("Status Request").Index Then Return
        ' Retrieve the task ID.
        Dim taskID As Int32 = CInt(dataGridView1(0, e.RowIndex).Value)
        ' Retrieve the Employee object from the "Assigned To" cell.
        Dim assignedTo As Employee = TryCast(dataGridView1.Rows(e.RowIndex) _
            .Cells("Assigned To").Value, Employee)
        ' Request status through the Employee object if present. 
        If assignedTo IsNot Nothing Then
            assignedTo.RequestStatus(taskID)
        Else
            MessageBox.Show(String.Format( _
                "Task {0} is unassigned.", taskID), "Status Request")
        End If
    End Sub
End Class
注解
类 DataGridViewButtonCell 是用于显示类似按钮的 UI 的专用类型 DataGridViewCell 。
DataGridViewButtonColumn 是专用于保存此类型的单元格的列类型。 默认情况下, DataGridViewButtonColumn.CellTemplate 初始化为新的 DataGridViewButtonCell。 若要在现有 DataGridViewButtonCell之后对列中的单元格进行图案化,请将列的 CellTemplate 属性设置为要用作模式的单元格。
若要响应用户按钮单击,请处理 DataGridView.CellClick 或 DataGridView.CellContentClick 事件。 在事件处理程序中,可以使用 DataGridViewCellEventArgs.ColumnIndex 属性来确定按钮列是否发生了单击。 可以使用 DataGridViewCellEventArgs.RowIndex 属性来确定单击是否发生在特定按钮单元格中。
列的单元格相关属性是模板单元格的类似名称属性的包装器。 更改模板单元格的属性值将仅影响基于更改后添加的模板的单元格。 但是,更改列的单元格相关属性值将更新模板单元格和列中的所有其他单元格,并在必要时刷新列显示。
注意
启用视觉样式后,按钮列中的按钮将使用 ButtonRenderer绘制,并且通过属性(如) DefaultCellStyle 指定的单元格样式不起作用。
继承者说明
从 DataGridViewButtonCell 派生类并将新属性添加到派生类时,请务必重写 Clone() 方法,以在克隆操作期间复制新属性。 还应调用基类的 Clone() 方法,以便将基类的属性复制到新单元格。
构造函数
| DataGridViewButtonCell() | 初始化 DataGridViewButtonCell 类的新实例。 |