2014-04-27 77 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[])

希望這有助於。