c# - 如何向我的 DataGridView 中的某些(不是全部)列添加按钮?

标签 c# winforms datagridview

我正在尝试更新此 DataGridView 对象,如果值 == "bob",则在其名称旁边的列中将有一个按钮,否则我不希望出现任何按钮。

DataGridViewTextBoxColumn valueColumn = new DataGridViewTextBoxColumn();
DataGridViewButtonColumn buttonColumn = new DataGridViewButtonColumn();

buttonColumn.ReadOnly = true;
buttonColumn.Visible = false;

this.dgv.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
valueColumn,
buttonColumn,
});

//elsewhere...

if(value == "bob")
{
    Button button = new Button()
    {
        Text = "null",
    };

    index = dgv.Rows.Add(value, button);
    DataGridViewButtonCell buttonCell = dgv.Rows[index].Cells[2] as DataGridViewButtonCell;
    buttonCell.Visible = true;
}
else
{
    dgv.Rows.Add(value);
}

但是,因为我不能在单元格上设置可见,所以这不起作用。有没有一种方法可以仅向 Value == "bob"的行添加按钮?

最佳答案

这是我以前用过的一个巧妙的小技巧:

不使用 DataGridViewButtonColumn,而是使用 DataGridViewTextBoxColumn 并在适当的地方添加 DataGridViewButtonCell。

例如

    private void button1_Click(object sender, EventArgs e)
    {
        // Iterate through each of the rows.
        for (int i = 0; i < dgv.RowCount - 1; i++)
        {
            if (dgv.Rows[i].Cells[0].Value.ToString() == "bob")
            {
                // Here is the trick.
                var btnCell = new DataGridViewButtonCell();
                dgv.Rows[i].Cells[1] = btnCell;
            }
        }
    }

在上面的示例中,我有两个 DataGridViewTextBoxColumns 并在按钮单击事件中遍历每一行。我检查第一列以查看它是否包含“bob”,如果包含,我在它旁边的列中添加一个按钮。您可以根据需要使用此技巧(即单击按钮、RowsAdded 事件、CellEndEdit 事件等)。以不同的方式进行实验。希望这对某人有帮助!

关于c# - 如何向我的 DataGridView 中的某些(不是全部)列添加按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4262147/

相关文章:

c# - 我应该在哪里存储应用程序的 TrayIcon?

c# - CIL 'fault' 子句与 C# 中的 'catch' 子句有何不同?

C# 打开一个新窗体并关闭另一个窗体

c# - 部署后,应用程序退出/关闭时APPCRASH错误C#

c# - WinForms 自定义 3 纽扣单元

c# - 从父控件接收 MouseMove 事件

c# - 如何将 DataGridView 文本框列设置为多行?

c# - 使用参数的 npgsql 语句

c# - 确保文本在 dataGridView 列中换行

c# - 需要在 Winform 应用程序中添加 DataGridViewCheckBoxColumn