2016-06-22 43 views
0

データベースからデータを取得した後にdataGridViewセルの色を付ける必要があります。セルテキストに「X」が付いている場合は、セルをGreenYellowカラーで色付けします。私はコードを書こうとしたが、うまくいかなかった。C#のテキスト条件でdataGridViewセルの色を変更する方法

これは私がこれまで持っているコードです:

private void button2_Click(object sender, EventArgs e) 
    { 
     string constring = "Data Source = localhost; port = 3306; username = root; password = 0159"; 
     MySqlConnection conDataBase = new MySqlConnection(constring); 
     MySqlCommand cmdDataBase = new MySqlCommand("Select * from TopShineDB.Table1 ;", conDataBase); 
     using (MySqlConnection conn = new MySqlConnection(constring)) 
     { 
      try { 
      MySqlDataAdapter sda = new MySqlDataAdapter(); 
      sda.SelectCommand = cmdDataBase; 
      DataTable dt = new DataTable(); 
      sda.Fill(dt); 

       foreach (DataRow item in dt.Rows) 
       { 
        int n = dataGridView1.Rows.Add(); 
        dataGridView1.Rows[n].Cells[0].Value = item["Timee"].ToString(); 
        dataGridView1.Rows[n].Cells[1].Value = item["CarColorNumber"].ToString(); 
        dataGridView1.Rows[n].Cells[2].Value = item["Interior"].ToString(); 
        dataGridView1.Rows[n].Cells[3].Value = item["Exterior"].ToString(); 

        if (dataGridView1.CurrentCell.Value == item["Interior"] + " X".ToString()) 
        { 
         dataGridView1.CurrentCell.Style.BackColor = Color.GreenYellow; 
        } 
       } 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 

すべてのアイデア、私はそれを動作させることができますか?

ありがとうございました

+0

私はコードを編集しました。それは、データベースからデータを取得するためにボタンクリックで機能するはずです。 –

+0

a) 'inter'とは何ですか? b) '' X "'はすでに文字列です! c)現在のセルがあると仮定しないでください!代わりに処理している行の右のセルを変更してください!! – TaW

+0

@TaW申し訳ありませんが、回答のためにコード –

答えて

1

変更するセルのスタイルを設定する必要があります。

データをロードする場所とScrollイベントに以下のメソッドを含めると、セルが表示されているときにのみ、必要に応じてセルが色付けされます。 これは、多くの行

public void SetRowColor() 
{ 
    try 
    { 
     for (int i = 0; i < this.dataGridView.Rows.Count; i++) 
     { 
      if (this.dataGridView.Rows[i].Displayed) 
      { 
       if (this.dataGridView.Columns.Contains("Interior")) 
       { 
        if ((int)this.dataGridView.Rows[i].Cells["Interior"].Value == "X") 
        { 
         this.dataGridView.Rows[i].Cells["Interior"].Style.BackColor = Color.Green; 
         this.dataGridView.Rows[i].Cells["Interior"].Style.ForeColor = Color.White; 
         this.dataGridView.InvalidateRow(i); 
        } 
        else 
        { 
         this.dataGridView.Rows[i].Cells["Interior"].Style.BackColor = Color.White; 
         this.dataGridView.Rows[i].Cells["Interior"].Style.ForeColor = Color.Black; 
         this.dataGridView.InvalidateRow(i); 
        } 
       } 
      } 
     } 
    } 
} 

希望を持っている場合、これはあなたが必要なものにあなたが近づく、重要なパフォーマンスの問題です。

トマス

+0

を修正しました。そのセルの値は「X」だけではありません。ユーザーがテーブルを保存する前に書き込む特定の名前です。今私が望むのは、セルに "X"がある場合(例:David X)、バックカラーをGreenYellowにします。 –

+0

@ Tarek: .... Value.ToString()。( "X")が含まれています –

+0

それは働いています:)ご協力いただきありがとうございます。 –

関連する問題