简体   繁体   English

有条件地在DataGridView中显示按钮吗?

[英]Conditionally show buttons in DataGridView?

How to show buttons in cells of DataGridView if, for example, column A has value? 例如,如果列A具有值,如何在DataGridView的单元格中显示按钮?

private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    var dgv = (DataGridView)sender;
    if (dgv.Columns[e.ColumnIndex].Name == "btn")
    {
        var hide= dgv.Rows[e.RowIndex].Cells[dgv.Columns["A"].Index].Value is DBNull;
        var cell = dgv.Rows[e.RowIndex].Cells[dgv.Columns["B"].Index];
        if (hide)
        {
            //cell.Value = null;
            //cell = new DataGridViewTextBoxCell();
            cell.Visible = false; // This dosn't work
        }
    }
}

Probably the best way to do this is to bind to the Item_DataBound (I believe that's what it's called) on the grid view. 可能最好的方法是在网格视图上绑定到Item_DataBound(我相信这就是它的名字)。 Then check the column to see if it contains the value you need. 然后检查该列以查看其是否包含所需的值。 Then you can hide specific controls in the cell like this (using most of your code in your post): 然后,您可以像这样在单元格中隐藏特定的控件(使用帖子中的大多数代码):

cell.Controls[0].Visible = false;

Create a custom DataGridView and CustomDataGridViewColumn for it and assign the property to set visible and invisible particular cell button. 为此为其创建一个自定义DataGridViewCustomDataGridViewColumn并分配该属性以设置visibleinvisible特定单元格按钮。 here is an example that demonstrate how to create custom column for datagridview. 这是一个示例,演示如何为datagridview创建自定义列。 http://www.codemag.com/Article/0707061 otherwise it is not possible to make any cell button directly either visible or invisible. http://www.codemag.com/Article/0707061否则,无法使任何单元格按钮直接可见或不可见。

You need to cast button containing cell to DataGridViewButtonCell . 您需要将包含单元格的按钮强制转换为DataGridViewButtonCell The Cell can be cast to this class if it is Button Cell . 如果CellButton Cell ,则可以将其强制转换为此类。

Use this: 用这个:

var cell = dgv.Rows[e.RowIndex].Cells[dgv.Columns["B"].Index] as DataGridViewButtonCell;
cell.Visible = false;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM