2013-08-02 25 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>"; 
    } 
}