2012-08-13 29 views
0

我已經設置了一個數據網格視圖並將其鏈接到我的數據並用適配器填充它,所有工作都很好。我想要做的是在數據網格視圖的開始處添加一列,並將圖像添加到第一列,該列中當前第一列的文件名將作爲第二列結束。從datattable適配器中單獨填充datagridview列

我已經添加了列併爲圖像設置了它,並且如果未設置該值,還設置了默認圖像。我無法弄清楚如何讀取column2中的內容,然後使用文件名(根據我的命名方案進行編輯)將圖像加載到column1中。我不知道是否需要對網格視圖,數據集適配器或其他位置執行此操作。我試着迭代拋出行讀取cell2然後加載圖像的cell1,但我不能設置currentrow。

我結束了使用CellPainting,因爲CellFormating給我一些奇怪的輸出。以下是我使用的代碼。 Cells [0]是我想要放置圖像的單元格.Cell [1]是我用作文件名的圖像的名稱。

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) 
    { 
     string monsterName = ""; 

     try 
     { 
      if (this.dataGridView1.Columns[e.ColumnIndex].Name == "monsterNameDataGridViewTextBoxColumn") 
      { 
       if (e.Value != null && e.RowIndex > -1) 
       { 
        monsterName = (string)this.dataGridView1.Rows[e.RowIndex].Cells[1].Value; 
        this.dataGridView1.Rows[e.RowIndex].Cells[0].Value = new Bitmap(@"C:\Users\Chad\Pictures\Dark Summoner\C_" + monsterName + @".png"); 
       } 
      } 
     } 

     catch (ArgumentException) 
     { 
      toolStripStatusLabel1.Text = monsterName + " image file does not exist."; 
     } 

    } 

回答

0

你可以用幾種方法處理這個問題。

1)處理datagridview的CellFormatting事件並在其中填充單元格的圖像。該事件有一個參數,可以訪問它試圖格式化的當前行/列。所以你可以讀取單元格2中的圖像文件,並在此基礎上設置單元格1的圖像。

2)預先填充數據源中的圖像數據。因此,例如,如果dataadapter填充DataTable,則可以在加載數據表後加載/填充數據表中的圖像。

+0

被海報取消 – 2012-08-19 21:36:30