2012-08-02 65 views
12

我有一个现有的应用程序,需要在DataGridView单元格中显示图像以指示记录是否具有与其关联的特定标志(不是用户可编辑,这来自数据库)。如何从DataTable填充时禁用DataGridView图像列中的空图像

如果有标志,我会显示相应的图像,如果没有标志,我不想在列中显示任何内容。

DataGridView列不是在Visual Studio设计器中创建的,否则这很容易。我可以在列上设置NullValue属性。相反,当所有数据加载到DataTable中时,在运行时创建列,然后从该DataTable创建DataView,然后将DataGridView的数据源设置为DataView。

我不能完全重写这个,否则我只是在VS Designer中定义列,而不是这种让数据表定义列的荒谬方式。

那么我的问题是,我怎样才能让底图数据表有空的时候带图像的列什么都不显示?

下面是一些伪C#来说明我的意思。请记住,我没有写它来使用这样的两个DataTable;它是这样,当我不得不把它交给我,我不想做太大改动只是为了添加新列...

DataTable rawData = someMethodThatReturnsMyRawData(); 
DataTable data = new DataTable(); 
data.Columns.Add("Flags", typeof(Image)); 
data.Columns.Add("SomeOtherColumn"); 

foreach (DataRow rawDataRow in rawData.Rows) 
{ 
    DataRow dataRow = data.NewRow(); 
    bool hasFlagType1 = false; 
    bool hasFlagType2 = false; 

    if (rawDataRow["FlagType1ID"] != DBNull.Value) 
    { 
     hasFlagType1 = true; 
    } 

    if (rawDataRow["FlagType2ID"] != DBNull.Value) 
    { 
     hasFlagType2 = true; 
    } 

    if (hasFlagType1 && hasFlagType2) 
    { 
     dataRow[0] = Properties.Resources.BothFlagsImage; 
    } 
    else if (hasFlagType1) 
    { 
     dataRow[0] = Properties.Resources.FlagType1Image; 
    } 
    else if (hasFlagType2) 
    { 
     dataRow[0] = Properties.Resources.FlagType2Image; 
    } 
    else 
    { 
     //If neither flag set, I don't want it to show anything, 
     //but if I leave it as null, a little box with an X in it shows up 
     //I could set it to some transparent GIF here, but that seems lame 
    } 

    dataRow[1] = rawDataRow["SomeOtherColumn"]; 

    data.Rows.Add(dataRow);   
} 

DataView dv = new DataView(data, string.Empty, "SomeOtherColumn ASC", DataViewRowState.CurrentRows); 

this.emptyDataGridViewFromDesigner.DataSource = dv; 

// How can I modify the column "Flags" at this point to show nothing if the value is null? 

编辑:下面是截图,所以你可以看到我是什么意思通过与X的小盒子 - 这些都是空...

DataGridView with Null Images

而且,它必须是.NET 3.5,所以如果有在.NET 4.0中的解决方案而已,我走了运气。

回答

25

我想通了这一点......

不得不转换列作为DataGridViewImageColumn,然后设置DefaultCellStyle.NullValue为该列设置为空。从上面我举的例子,你会做这样的......

((DataGridViewImageColumn)this.emptyDataGridViewFromDesigner.Columns["Flags"]).DefaultCellStyle.NullValue = null; 

我想我偷步问在这里,但希望这可以帮助别人的某个时候。

+0

如何在VB.NET中执行相同操作? =我猜想没有? – 2016-03-17 06:52:02

+0

我有这个解决方案不适用于最后一行 – camino 2017-01-29 16:28:58

2

要修复整个网格,只需将此代码添加到Form构造函数。 (并更改您的dataGrid的名称):

 Load += delegate 
     { 
      // remove default [x] image for data DataGridViewImageColumn columns 
      foreach (var column in dataGridView1.Columns) 
      { 
       if (column is DataGridViewImageColumn) 
        (column as DataGridViewImageColumn).DefaultCellStyle.NullValue = null; 
      } 
     };