我有一个包含多列和多行数据的DataGridView
。其中一列是DataGridViewCheckBoxColumn
(基于行中的其他数据),我希望在某些行中选择“隐藏”复选框。我知道如何将其设置为只读,但我希望它根本不显示,或者至少显示与其他复选框不同(灰显)。这个是可能的吗?
发布于 2011-10-06 00:06:52
一些解决方法:将其设置为只读,然后将颜色改回灰色。对于一个特定的单元格:
dataGridView1.Rows[2].Cells[1].Style.BackColor = Color.LightGray;
dataGridView1.Rows[2].Cells[1].ReadOnly = true;
或者,更好但更“复杂”的解决方案:
假设你有两列:第一列是数字,第二列是复选框,当数字大于2时,它们应该是不可见的。你可以处理CellPainting
事件,只绘制边框(例如。背景),并打破休息的绘画。为DataGridView添加事件CellPainting
(可选测试DBNull值,以避免在空行中添加新数据时出现异常):
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
//check only for cells of second column, except header
if ((e.ColumnIndex == 1) && (e.RowIndex > -1))
{
//make sure not a null value
if (dataGridView1.Rows[e.RowIndex].Cells[0].Value != DBNull.Value)
{
//put condition when not to paint checkbox
if (Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value) > 2)
{
e.Paint(e.ClipBounds, DataGridViewPaintParts.Border | DataGridViewPaintParts.Background); //put what to draw
e.Handled = true; //skip rest of painting event
}
}
}
}
它应该可以工作,但是如果您手动更改第一列中的值,您必须刷新第二个单元格,因此添加另一个事件,如CellValueChanged
:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
dataGridView1.InvalidateCell(1, e.RowIndex);
}
}
发布于 2011-10-05 23:55:55
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcheckboxcell.aspx
DataGridViewCheckBoxCell.Visible = false;
编辑:哦,等等,它是只读的。德尔普。
在这种情况下,请尝试用空的DataGridViewTextBoxCell替换单元格。
发布于 2011-10-06 00:33:35
取自Customize the Appearance of Cells in the Windows Forms DataGridView Control,如果单元格处于只读模式,则可以捕获CellPainting事件而不绘制单元格。例如:
public Form1()
{
InitializeComponent();
dataGridView1.CellPainting += new
DataGridViewCellPaintingEventHandler(dataGridView1_CellPainting);
}
private void dataGridView1_CellPainting(object sender,
System.Windows.Forms.DataGridViewCellPaintingEventArgs e)
{
// Change 2 to be your checkbox column #
if (this.dataGridView1.Columns[2].Index == e.ColumnIndex && e.RowIndex >= 0)
{
// If its read only, dont draw it
if (dataGridView1[e.ColumnIndex, e.RowIndex].ReadOnly)
{
// You can change e.CellStyle.BackColor to Color.Gray for example
using (Brush backColorBrush = new SolidBrush(e.CellStyle.BackColor))
{
// Erase the cell.
e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
e.Handled = true;
}
}
}
}
唯一需要注意的是,当您更改某个DataGridViewCheckBox
单元格的ReadOnly
属性时,需要调用dataGridView1.Invalidate();
。
https://stackoverflow.com/questions/7664115
复制相似问题