从DataTable填充时,如何在DataGridView图像列中禁用Null图像

Jim*_*Jim 14 .net c# datagridview image winforms

我有一个现有的应用程序,需要在DataGridView单元格中显示一个图像,以表示该记录是否具有与之关联的特定标志(不是用户可编辑的,这来自数据库).

如果有一个标志,我会显示相应的图像,如果没有标记,我希望列中没有显示任何内容.

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

我不能完全重写这个,否则我只是在VS Designer中定义列,而不是仅仅从DataTable中定义列的荒谬方式.

那么我的问题是,当基础数据表为空时,如何使图像的列显示为什么?

这里有一些伪C#来证明我的意思.记住,我没有写它来使用这样的两个DataTables; 当我把它递给我时,就是那种方式,我不想仅仅为了添加一个新列而做出重大改变......

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?
Run Code Online (Sandbox Code Playgroud)

编辑:这是一个截图,所以你可以看到我的意思是带有X的小盒子 - 这些都是空的......

带有空图像的DataGridView

此外,它必须是.NET 3.5,所以如果只有.NET 4.0的解决方案,我运气不好.

Jim*_*Jim 30

我想出来了......

必须将列强制转换为DataGridViewImageColumn,然后将该列的DefaultCellStyle.NullValue设置为null.从我上面的例子中,你就是这样做的......

((DataGridViewImageColumn)this.emptyDataGridViewFromDesigner.Columns["Flags"]).DefaultCellStyle.NullValue = null;
Run Code Online (Sandbox Code Playgroud)

我想我在这里问了一下枪,但希望这有时可以帮助别人.


Net*_*ert 5

new Bitmap(1,1);简单地分配给单元格的.Value属性并继续前进要容易得多。每当我尝试将 NULL 分配给单元格的值时,即使修改了值,我的应用程序也会抛出异常DefaultCellStyle.NullValue

像这样的事情每次都会按预期工作,没有任何麻烦或神秘/晦涩的设置:

dataGridView1.Rows[index].Cells["CellName"].Value = isFlag ? Properties.Resources.FlagImage : new Bitmap(1,1);
Run Code Online (Sandbox Code Playgroud)

  • 显然值得一提的是,在具有大量可能需要此分配的单元格的 DataGridView 中,最好创建一个 Bitmap 实例并每次分配它,而不是创建可能数千个单独的 Bitmap() 对象来实现相同的效果最终结果。 (2认同)