2017-05-28 4 views
0

私はすべての行にセルを入れたいと思います。請求書を含むセルが開いている場合は、特定のピクチャを表示したい場合は、そのセルに別のピクチャを表示する必要があります。請求書ステータスのイメージを含む列を追加キャンセルまたはオープンC#

エラー画像:

enter image description here

コード:

this.dgvBills.DataSource = bill.SearchBills(txtSearch.Text, coBoxState.Text); 
       DataGridViewImageColumn img = new DataGridViewImageColumn(); 
       img.Name = "img"; 
       img.HeaderText = "Image Column"; 
       img.ValuesAreIcons = true; 
       dgvBills.Columns.Add(img); 
       int number_of_rows = dgvBills.RowCount; 
       for (int i = 0; i < number_of_rows; i++) 
       { 
        if (dgvBills.Rows[i].Cells[11].Value.ToString() == "open") 
        { 

         dgvBills.Rows[i].Cells["img"].Value = pbox.Image; 
        } 
        else 
        { 

         dgvBills.Rows[i].Cells["img"].Value = pbox.InitialImage; 
        } 

答えて

1

これにはいくつかのアプローチがあります。このアイコンのような純粋に視覚的なインジケータの場合は、セルの書式設定中にアイコンを表示する方がよい場合があります。

は、ハンドルのDataGridViewの CellFormatting event-

private void dgvBills_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    switch (dgvBills.Columns[e.ColumnIndex].Name) 
    { 
     case "img": // The name of your image column 

      if (dgvBills.Rows[e.RowIndex].Cells[11].Value.ToString() == "open") 
       e.Value = pbox.Image; // image stored in a PictureBox 
      else 
       e.Value = pbox.InitialImage; // image stored in a PictureBox 

      break; 
    } 
} 

あなたのイメージソースを変更することで、さらにこれをクリーンアップすることができます。 PictureBoxを捨て、プロジェクトのリソースを使用します。例として、開いた状態と閉じた状態を表す2つの16x16 PNGアイコンを作成した場合は、それらをプロジェクトリソースにopen_invoiceclosed_invoiceとして追加できます。

その後、値の割り当ては

e.Value = new Bitmap(Properties.Resources.open_invoice); 
e.Value = new Bitmap(Properties.Resources.closed_invoice); 

あなたのコード - に読みやすくなったり、あなたがあなたのデータソースを管理している場合は

e.Value = new Bitmap(1, 1); 

icon-「空白」を設定する必要がある場合これをもっときれいにすることができます。 bill.SearchBills()関数がList<Bill>を返すとします。次にBillsクラスを設計して、クラスプロパティとしてBitmapを直接返すことができます。

public class Bill 
{ 
    public Image OpenClosedIcon 
    { 
     get 
     { 
      return IsOpen 
       ? new Bitmap(Properties.Resources.open_invoice) 
       : new Bitmap(Properties.Resources.closed_invoice); 
     } 
    } 

    public bool IsOpen 
    { 
     get; 
     set; 
    } 

    // The rest of your Bill class definition... 

} 

これはデータバインディングの利点です。データソースがそれを提供すると、DataGridViewはビットマップフィールドを認識し、DataGridViewImageColumnで正しく処理できます。

最も簡単な方法は、通常、DataGridViewの組み込み列デザイナーを使用して、必要な列を作成することです。 DataGridViewImageColumnの場合は、DataPropertyNameをクラスフィールド名に設定します。OpenClosedIcon

完全に準備されたデータソースでは、CellFormattingハンドラはまったく必要ありません。

関連する問題