2014-04-27 34 views
0

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

这是我如何过滤数据什么,我想放在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的行的图标列中。

+0

我不太明白这个问题以及它如何对应问题标题。你在绑定dgv中显示图像还是编辑某个单元格时遇到问题?你能重新格式化吗? –

+0

@d_z问题标题没问题,但我稍微改了一下。我如何根据数据集中的一段数据将某一列设置为特定图像? – Jerry

回答

0

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

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[])

希望这有助于。