(DataGridView + Binding)バインドされたオブジェクトに応じて線を色付けする方法は?

StackOverflow https://stackoverflow.com/questions/284420

質問

バインドされたオブジェクトのプロパティに応じて、特定の行に背景色を追加したい。

私が持っている(そして機能している)ソリューションは、イベント DataBindingComplete を使用することですが、それが最良のソリューションだとは思いません。

イベントは次のとおりです。

    private void myGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {

        for (int i = 0; i < this.myGrid.Rows.Count; i++)
        {
            if((this.myGrid.Rows[i].DataBoundItem as MyObject).Special)
            {
                this.myGrid.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128);
            }
        }
    }

他に優れているオプションはありますか?

役に立ちましたか?

解決

RowPostPaintにイベントハンドラーを追加することもできます:

dataGridView1.RowPostPaint += OnRowPostPaint;

void OnRowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    MyObject value = (MyObject) dataGridView1.Rows[e.RowIndex].DataBoundItem;
    DataGridViewCellStyle style = dataGridView1.Rows[e.RowIndex].DefaultCellStyle;

    // Do whatever you want with style and value
    ....
}

他のヒント

WinFormsを実際に使用することはあまりありませんが、ASPでは 'ItemDataBound'メソッドを使用します。 DataGridのWindowsフォームに類似したものはありますか?

その場合、そのメソッドのイベント引数には、DataGrid行とともに、データバインドされたアイテムが含まれます。したがって、一般的なコードは次のようになります(構文はおそらくオフです):

if(((MyObject)e.Item.DataItem).Special)
   e.Item.DefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128);

いくつかのことをお勧めします:

  • _OnRowDataboundでの行の変更を見る
  • コードに色を設定しないでください!!!これは大きな間違いです。 attributesプロパティを使用して、cssclassを設定します。まだこれをしている人々に指を振る。

実装に苦労している場合はお知らせください。スニペットを投稿します。

private void myGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{

    foreach (DataGridViewRow row in myGrid.Rows)
    {
        if((row.DataBoundItem as MyObject).Special)
        {
            row.DefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128);
        }
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top