我有一个DataGridView,我想在我的网格中有一个列,其中有一些单元格显示一个按钮,一些单元格不包含该按钮。 为了解决这个问题,我添加了一个DataGridViewButtonColumn,我编写了这个方法,我调用这些方法将行添加到我的列中:
private void AttachNewRow(bool validRow)
{
DataGridViewRow newRow = GetNewRow();
if (validRow)
{
newRow.Cells["Info"].Value = "Click me";
}
else
{
// Here I would like to hide the button in the cell
newRow.Cells["Info"].Value = null;
}
}
问题是当我将单元格值设置为null时,我收到一个异常。 如何在没有按钮的情况下显示其中一些单元? 谢谢
答案 0 :(得分:2)
看起来GetNewRow()
会返回您在Row
已插入的DGV
。
如果该功能知道“信息”Column
是否包含Button
,它可以传递它,可能在Tag
中:
if (somecondiiotn) newRow.Columns["Info"].Tag = "Button";
然后你可以写:
private void AttachNewRow()
{
DataGridViewRow newRow = GetNewRow();
if ( newRow.Cells["Info"].Tag == null ||
newRow.Cells["Info"].Tag != "Button") return;
//..
如果otoh调用AttachNewRow()
的代码具有所需的知识,则可以在参数中传递它:
private void AttachNewRow(bool infoButton)
如果知识分子仅在以后可用,您仍然可以更改单个单元格。
更新
因为您现在将条件传递给方法,所以您可以采取相应的行动。
我不知道为什么你的代码会出现异常 - 我不知道。但要真正隐藏Button
,您应该将单元格更改为“正常”DataGridViewTextBoxCell
:
else
{
DataGridViewCell cell = new DataGridViewTextBoxCell();
newRow.Cells["Info"] = cell;
答案 1 :(得分:1)
您可以在RowAdded事件处理程序中尝试这样的操作。这里假设第三列是按钮列:
if (condition)
{
dataGridView1.Rows[e.RowIndex].Cells[2] = new DataGridViewTextBoxCell();
dataGridView1.Rows[e.RowIndex].Cells[2].ReadOnly = true;
}