如何在GridView的ItemTemplate中根据Status为Label应用Bootstrap类
Hey there! Let's get your GridView's Status labels styled with the correct Bootstrap badge classes. Here are two straightforward approaches to make this work:
Approach 1: Inline Binding in ASPX Markup
You can extend your existing inline ternary logic to set the CssClass property directly in the markup. This keeps all the styling logic right where you define the Label:
<asp:TemplateField HeaderText="Status"> <ItemTemplate> <asp:Label ID="lblStatus" runat="server" Text='<%# ((string)Eval("Status") == "Open") ? "Open" : "Closed" %>' CssClass='<%# ((string)Eval("Status") == "Open") ? "badge badge-success" : "badge badge-danger" %>'> </asp:Label> </ItemTemplate> </asp:TemplateField>
Just double-check that the Status value from your data source exactly matches the strings you're checking (it's case-sensitive, so "open" vs "Open" would behave differently).
Approach 2: Code-Behind with RowDataBound Event
If you want more flexibility (like handling additional status values later), use the GridView's RowDataBound event to set the class programmatically.
First, update your markup to remove the inline CssClass binding:
<asp:TemplateField HeaderText="Status"> <ItemTemplate> <asp:Label ID="lblStatus" runat="server" Text='<%# ((string)Eval("Status") == "Open") ? "Open" : "Closed" %>'> </asp:Label> </ItemTemplate> </asp:TemplateField>
Then add this code to your code-behind (C# example):
protected void YourGridView_RowDataBound(object sender, GridViewRowEventArgs e) { // Only target data rows (skip header/footer rows) if (e.Row.RowType == DataControlRowType.DataRow) { // Extract the Status value from the current row's data string status = DataBinder.Eval(e.Row.DataItem, "Status").ToString(); // Locate the Label control in the row Label lblStatus = (Label)e.Row.FindControl("lblStatus"); // Apply the matching Bootstrap badge class if (status == "Open") { lblStatus.CssClass = "badge badge-success"; } else if (status == "Close") // Match your actual data value here { lblStatus.CssClass = "badge badge-danger"; } // Add extra else-if blocks here if you need to handle more status types } }
Don't forget to link the event to your GridView in the markup:
<asp:GridView ID="YourGridView" runat="server" OnRowDataBound="YourGridView_RowDataBound"> <!-- Your other columns go here --> </asp:GridView>
Quick Reminder
Ensure you've included the Bootstrap CSS file in your page so the badge styles render properly. For example:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
内容的提问来源于stack exchange,提问作者Shonisani Ratshivhadelo

