【问题标题】:Formatting specific rows in a DataGridView格式化 DataGridView 中的特定行
【发布时间】:2014-04-27 21:54:11
【问题描述】:

我有一个名为 dataGridView1 的 DGV,它有两列,一个图像列和一个字符串列。我还有一个用于填充 DGV 的自定义数据集合。在我的特定应用程序中,每一行在字符串列中都有一个指定的字符串,在图像列中有两个图像之一。填充 DGV 时,我无法在图像列中显示正确的图像。

这就是我将数据过滤成我想要放入 DGV 的方式:

var match = Core.Set.Servers.Where(ServerItem => ServerItem.GameTag == text);

目前,我这样做是为了填充 DGV:

dataGridView1.AutoGenerateColumns = false;
source = new BindingSource(match,null);
dataGridView1.DataSource = source;

但是,图像单元格仅显示默认的损坏图像图标。我的图标位于

Directory.GetCurrentDirectory() + "//Images/favorite.png";

有没有使用 DataTable 甚至 BindingSource 的好方法?集合中的每个项目都有两个有用的功能:ServerItem.ServerName 和 ServerItem.IsFavorite。第一个是字符串,第二个是布尔值。我希望喜欢的图标显示在具有 IsFavorite==true 的每一行的图标列中。

【问题讨论】:

  • 我不太明白这个问题以及它与问题标题的对应关系。在绑定 dgv 中显示图像或编辑某些单元格时是否有问题?你能重新格式化一下吗?
  • @d_z 问题标题很好,但我稍微改了一下。如何根据数据集中的一条数据将一行中的列设置为特定图像?

标签: c# datagridview


【解决方案1】:

要根据数据值在绑定的 DataGridView 中显示图像,您应该处理 DataGridView 的CellFormatting 事件。我建议将图像存储在 ImageList 之类的内存结构中,以避免往返存储。这是一个sn-p:

List<Row> data = new List<Row>
{
    new Row { IsFavorite = true },
    new Row { IsFavorite = false },
};

dataGridView1.Columns.Add(new DataGridViewImageColumn(false));
dataGridView1.Columns[0].DataPropertyName = "IsFavorite";
dataGridView1.Columns[0].DefaultCellStyle.NullValue = null;
dataGridView1.DataSource = data;

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
        if (e.Value != null && e.Value is bool)
        {
            if ((bool)e.Value == true)
            {
                e.Value = imageList1.Images[0];
            }
            else
            {
                e.Value = null;
            }
        }
    }
}

public class Row
{
    public bool IsFavorite { get; set; }
}

还有另一个建议:结合部分路径,您可以使用Path.Combine(string[])

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2017-12-30
    • 2023-03-28
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多