动态修改 gridview 元素的 class

modify class of gridview element dynamically

我有一个网格视图:

<asp:GridView runat="server" ID="gv_patientMeds" Width="100%" AutoGenerateColumns="False" GridLines="Both" OnRowDataBound="gv_patientMeds_onRowDataBound">
    <Columns>
        <asp:TemplateField HeaderText="Edit" HeaderStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:Button ID="lb_editPatient" runat="server" CssClass="<%# Eval(Convert.ToInt32(Eval("recordId")) != 0 ? "btn-active" : "btn-inactive"); %>" Text="Delete" OnClientClick="SubmitDeleteMedicationChange(<%# Eval("updateClinicVisit_recordIdForDelete") %>);" UseSubmitBehavior = "false" />
            </ItemTemplate>
            <ItemStyle HorizontalAlign="Center" />
        </asp:TemplateField>
    </Columns>
</asp:GridView>

我这样加载数据:

gv_patientMeds.DataSource = theDataToBindInPopup;
gv_patientMeds.DataBind();

theDataToBindInPopup 只是自定义对象的列表。

如您所见,我正在尝试使用某种逻辑分配删除按钮的 class,其中 recordId 是 DataToBindInPopup 列表中对象之一的属性。 ASP 不过不喜欢这样。我得到 "server tag in not well formed".

在这种情况下,如何使用逻辑分配按钮的 class?

提前致谢。

用这个

替换你的 lb_editPatient 按钮

将双引号括在单引号内

<asp:Button ID="lb_editPatient" runat="server" 
CssClass='<%# (Convert.ToInt32(Eval("recordId")) != 0 ? "btn-active" : "btn-inactive") %>' Text="Delete" 
OnClientClick='SubmitDeleteMedicationChange(<%# Eval("updateClinicVisit_recordIdForDelete") %>)' UseSubmitBehavior = "false" />

尽管 Ganesh 和 fnostro 建议的内容可行,但您也可以在代码中设置逻辑:

protected void gv_patientMeds_onRowDataBound(object sender, GridViewRowEventArgs e)
        {   
            //Get data row view
            DataRowView drview = e.Row.DataItem as DataRowView;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //Find dropdown control
                Button btn= (Button)e.Row.FindControl("lb_editPatient");
                btn.CssClass= Convert.ToInt32(drview["recordId"]) != 0 ? "btn-active" : "btn-inactive"; 

            }
        }