2013-02-26 69 views
1

在asp.net應用程序中,我使用的是網格視圖控件,因爲我將數據綁定到中的label
如果數據爲空,則色行的應該是紅色
如果不是我的意思是,如果數據是存在綁定,則行綠色。 這是我的代碼:在gridview中行背景顏色?

<asp:TemplateField HeaderText ="Holiday Region"> 
    <ItemTemplate > 
     <asp:Label ID ="lblholdareg" runat ="server" Text ='<%# Eval("Holidaregion") %>' > 
     </asp:Label> 
    </ItemTemplate> 
</asp:TemplateField> 
+0

使用行數據綁定 – 2013-02-26 05:48:27

回答

2

你可以做它的gridviewrowdatabound功能如下

protected void RowDataBound(Object sender, GridViewRowEventArgs e) 
{ 
    if(e.Row.RowType == DataControlRowType.DataRow) 
    { 
     //change it according your cell number or find element 
     if(e.Row.Cells[0].Text != "") 
      e.Row.BackColor = Color.Green; 
     else 
      e.Row.BackColor = Color.Red; 
    } 
} 
+0

爲什麼下降投票? – 2013-02-26 05:57:48

+0

我取消了你的downvote,不知道你爲什麼被DV'd。你的解決方案並不完整,但它的方向是正確的。另一個答案是OP所要求的所有標籤顏色。 – 2013-02-26 08:32:54

+0

hi @Şhȇkhaṝ但事件沒有發射......, – Anjali 2014-06-07 04:34:43

0

嘗試是這樣的

<asp:TemplateField HeaderText ="Holiday Region"> 
    <ItemTemplate > 
    <asp:Label ID ="lblholdareg" runat ="server" 
    CSSClass='<%# (String.IsNullOrEmply(Eval("Holidaregion")))?"red:green" %>' 
    Text ='<%# Eval("Holidaregion") %>' > 
    </asp:Label> 

    </ItemTemplate> 
</asp:TemplateField> 

編輯:

而不是f與網格視圖內聯和代碼的東西背後ighting,只需用jQuery和實現同樣在客戶端

+0

ki會試着讓你知道murali – 2013-02-26 05:54:05

+0

你在哪裏設置'row-color'? – 2013-02-26 05:55:26

+0

@Shekhar,我希望你知道使用CSS。在這裏我添加到標籤中,也可以在行中應用相同的東西。使用CSS類控制樣式 – 2013-02-26 05:56:39

0
if(e.Row.RowType == DataControlRowType.DataRow) 
{ 
    Control l = e.Row.FindControl("Label1"); 
    ((Label)l).BackColor = System.Drawing.Color.Red; 
} 
+0

他想設置'行顏色' – 2013-02-26 06:01:28

+0

對,但在那一行他有一個標籤,所以他想設置標籤的背景顏色,而不是行顏色... – coder 2013-02-26 06:02:31

+0

我不請參閱有關標籤背景的問題。 – 2013-02-26 06:06:02

2

您需要處理RowDataBound事件,進入e.Row項目,並指定CSS類別或者直接設置背景顏色。我更喜歡設置一個CSS類,以便以後不用重新編譯就可以更改它的渲染。

<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"> 
    <Columns> 
     <asp:TemplateField HeaderText="Holiday Region"> 
      <ItemTemplate> 
       <asp:Label ID="lblholdareg" runat="server" Text='<%# Eval("Holidaregion") %>' /> 
      </ItemTemplate> 
     </asp:TemplateField> 
    </Columns> 
</asp:GridView> 

而且我有你使用一個DataTable作爲數據源的假設,更新代碼以滿足您的數據結構中的代碼隱藏:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    System.Data.DataRow row = (System.Data.DataRow)e.Row.DataItem; 
    if (row["Holidaregion"] == null || row["Holidaregion"].ToString().Trim().Length == 0) 
    { 
     e.Row.CssClass = "row-empty"; 
    } 
    else 
    { 
     e.Row.CssClass = "row-full"; 
    } 
}