我有一个现有的应用程序,它有一个新要求,即在 DataGridView 单元格中显示图像以指示记录是否具有与之关联的特定标志(用户不可编辑,这来自数据库)。
如果有标志,我会显示相应的图像,如果没有标志,我不想在列中显示任何内容。
DataGridView 列不是在 Visual Studio 设计器中创建的,否则这很容易。我可以只在列上设置 NullValue 属性。相反,列是在运行时创建的,当所有数据都加载到 DataTable 中时,然后从该 DataTable 创建 DataView,然后将 DataGridView 的数据源设置为 DataView。
我不能完全重写它,否则我将只在 VS Designer 中定义列,而不是这种只让列从 DataTable 定义的荒谬方法。
那么我的问题是,当基础数据表为 null 时,我怎样才能使带有 Images 的列不显示任何内容?
这里有一些伪 C# 来演示我的意思。请记住,我编写它并不是为了像这样使用两个数据表;当我把它交给我时就是这样,我不想仅仅为了添加一个新列而做出重大改变......
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 的小框的意思 - 这些都是空值...
此外,它必须是 .NET 3.5,所以如果仅在 .NET 4.0 中有解决方案,我就不走运了。
最佳答案
我想通了...
必须将该列转换为 DataGridViewImageColumn,然后将该列的 DefaultCellStyle.NullValue 设置为 null。从我上面的例子,你会这样做......
((DataGridViewImageColumn)this.emptyDataGridViewFromDesigner.Columns["Flags"]).DefaultCellStyle.NullValue = null;
我想我是冒昧地问这里,但希望这有时能对其他人有所帮助。
关于c# - 从 DataTable 填充时如何禁用 DataGridView 图像列中的空图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11782112/