2017-01-19 4 views
1

Мне было интересно, есть ли способ покрасить все пустые ячейки в GridView оранжевым цветом. Столбцы в моем GridView динамически генерируются. Любая помощь приветствуется.Цвет всех пустых ячеек в ASP.NET GridView

Спасибо!

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    //check if the rowtype is a datarow 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 


     //loop all the cells in the row 
     for (int i = 0; i < e.Row.Cells.Count; i++) 
     { 
      int value = 0; 

      //try converting the cell value to an int 
      try 
      { 
       value = Convert.ToInt32(e.Row.Cells[i].Text); 
      } 
      catch 
      { 
      } 

      //check the value and set the background color 
      if (value == "") 
      { 
       e.Row.Cells[i].BackColor = Color.Green; 
      } 
      else 
      { 
       e.Row.Cells[i].BackColor = Color.White; 
      } 
     } 
    } 
} 
+0

Событие OnRowDataBound - это ваша отправная точка. Там вы можете пройти через все ячейки и проверить их ценность. –

+0

Посмотрите [ЗДЕСЬ] (http://stackoverflow.com/questions/31528633/how-to-change-gridview-cell-color-based-on-condition-using-c-sharp/31529889#31529889). – jsanalytics

+0

Можете ли вы показать мне, как именно вы это делаете? –

ответ

3

Попробуйте это:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
     for (int i = 0; i < e.Row.Cells.Count; i++) 
     { 
      if (e.Row.Cells[i].Text == "&nbsp;") 
       e.Row.Cells[i].BackColor = Color.Orange; 
     } 
    } 

enter image description here

+0

Спасибо, сэр! –

1

Вы можете использовать RowDataBound событие для этого, как вы делаете сейчас. Но есть проблема. Вы создаете int value, но затем попробуйте сравнить value с строкой if (value == ""). это не сработает.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    //check if the row is a datarow 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     //cast the row back to a datarowview 
     DataRowView row = e.Row.DataItem as DataRowView; 

     //loop all columns in the row 
     for (int i = 0; i < e.Row.Cells.Count; i++) 
     { 
      //check if the string is null of empty in the source data 
      //(row[i]) instead of e.Row.Cells[i].Text 
      if (string.IsNullOrEmpty(row[i].ToString())) 
      { 
       e.Row.Cells[i].BackColor = Color.Green; 
      } 
      else 
      { 
       e.Row.Cells[i].BackColor = Color.White; 
      } 
     } 
    } 
} 
+0

Спасибо за помощь! –