[英]How to hide CheckBox in DataGridView if value of cell is null
[英]How to hide a particular checkbox cell in datagridview
我有一個datagridview
,它有一些textboxtype列和一個checkboxtype列。 CheckBoxColumn與bool類型屬性綁定。
我希望如果選中復選框,它會在網格中看到,否則不會如圖所示。
我在數據綁定完成時添加了一些代碼,但它給出了編譯時錯誤"Property or indexer 'System.Windows.Forms.DataGridViewCell.Visible' cannot be assigned to -- it is read only"
private void dgvleftEdit_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
var reportLogoList = cWShowInvoicePaymentDetailsBindingSource.List as IList<CWShowInvoicePaymentDetails>;
foreach (DataGridViewRow row in dgvleftEdit.Rows)
{
var objReport = row.DataBoundItem as CWShowInvoicePaymentDetails;
var findItem = from f in reportLogoList
//where f.fReportID == objReport.fKey
select f;
if (objReport.IsImage == false)
{
this.dgvleftEdit.Rows[row.Index].Cells[7].Visible = false;
}
else
{
this.dgvleftEdit.Rows[row.Index].Cells[7].Visible = true;
}
}
}
是否可以在datagridview中隱藏特定單元格?
我想這就是你想要的,如果不是為了原因留下一些評論:
//CellPainting event handler for your dataGridView1
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {
if (e.ColumnIndex > -1 && e.RowIndex > -1 && dataGridView1.Columns[e.ColumnIndex] is DataGridViewCheckBoxColumn){
if (e.Value == null || !(bool)e.Value) {
e.PaintBackground(e.CellBounds, false);
e.Handled = true;
}
}
}
//CellBeginEdit event handler for your dataGridView1
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e){
if (dataGridView1.Columns[e.ColumnIndex] is DataGridViewCheckBoxColumn){
object cellValue = dataGridView1[e.ColumnIndex, e.RowIndex].Value;
e.Cancel = cellValue == null || !(bool)cellValue;
}
}
將DataGridVIewCheckBoxColumn
更改為DataGridViewImageColumn
然后在datagridview.CellFormatting
處理程序中:
private void datagridview_CellFormatting(object sender,
dataGridViewCellFormattingEventArgs e)
{
if (e.RowIndex >= 0 && dataGridView1.Columns[e.ColumnIndex] is DataGridViewImageColumn)
{
if (e.Value != null && (bool)e.Value == true)
{
e.Value = My.Resources.yourCheckedImage;
}
else
{
e.Value = null;
}
}
}
然后單元格更新可以使用MouseDown
處理程序或Click
, Enter
..etc的其他處理程序處理。
private void datagridview_MouseDown(Object sender, MouseEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
DataGridView.HitTestInfo click = dgv.HitTest(e.Location.X, e.Location.Y);
//If your have predefined columns, then maybe better compare by Column.name
if(click.RowIndex >= 0 && dgv.Columns(click.ColumnIndex) is DataGridViewImageColumn)
{
DataGridViewCell cellTmp = dgv.Row(click.RowIndex).Cells(click.ColumnIndex);
if (cellTmp.Value == null)
{
cellTmp.Value = My.Resources.yourCheckedImage;
}
else
{
cellTmp.Value = null;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.