2013-08-02 24 views
0

我想让它如此,如果在不包含值的特定列中有一个单元格,我希望该单元格改变颜色。在RowDataBound中选择特定列

我目前没有任何示例代码可以显示,但如果有人可以帮忙,我将不胜感激。

回答

1

RowDataBound事件应该喜欢这个

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
     if (e.Row.RowType == DataControlRowType.DataRow) 
     { 
      if (e.Row.Cells[0].Text == "open") 
      { 
       e.Row.Cells[0].ForeColor = System.Drawing.Color.Red; 
      } 
      else if (e.Row.Cells[0].Text == "close") 
      { 
       e.Row.Cells[0].ForeColor = System.Drawing.Color.Black; 
      } 
      else 
      { 
       e.Row.Cells[0].ForeColor = System.Drawing.Color.Green; 
      } 
     } 
    } 
0

首先,您需要定义标记一个GridView,像这样:

<asp:GridView id="GridView1" emptydatatext="No data available." runat="server" onrowdatabound="GridView1_RowDataBound" > 
    <Columns> 
     <asp:boundfield datafield="CustomerID" headertext="Customer ID"/> 
     <asp:boundfield datafield="CompanyName" headertext="Company Name"/> 
     <asp:boundfield datafield="Address" headertext="Address"/> 
     <asp:boundfield datafield="City" headertext="City"/> 
     <asp:boundfield datafield="PostalCode" headertext="Postal Code"/> 
     <asp:boundfield datafield="Country" headertext="Country"/> 
    </Columns> 
</asp:GridView> 

注意:您GridViewDataSource需要有匹配您GridView定义的datafield值公共属性名称。

其次,你需要实现你的GridView定义的onrowdatabound事件,它指向一个名为GridView1_RowDataBound方法,就像这样:

protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e) 
{ 
    if(e.Row.RowType == DataControlRowType.DataRow) 
    { 
     // Put logic here to check particular cell value 
     // Here is an example of changing the second cell (`Cells` collection is zero-based) to italic 
     e.Row.Cells[1].Text = "<i>" + e.Row.Cells[1].Text + "</i>"; 
    } 
}