如果来自 SQL 服务器的列数据 returns 为空,如何隐藏 DataList 中的 table 行

How to hide table rows in a DataList if column data returns null from SQL Server

如果来自 SQL 服务器的列数据 returns 为空(对于每个单独的列),我需要隐藏 DataList 中的 table 行。我让它工作成功,但这种方法会非常乏味,因为我的 table 中有大约 100 行。当然还有更简单的方法。

这是我的 C# 代码:

protected void DataList1_ItemDataBound1(object sender, DataListItemEventArgs e)
{
    if ((String.IsNullOrEmpty(((Label)e.Item.FindControl("lblAccountStatus")).Text)))
    {
        HtmlTableRow row = (HtmlTableRow)e.Item.FindControl("rowAccountStatus");
        row.Visible = false;
    }

    if ((String.IsNullOrEmpty(((Label)e.Item.FindControl("lblAccountName")).Text)))
    {
        HtmlTableRow row = (HtmlTableRow)e.Item.FindControl("rowAccountName");
        row.Visible = false;
    }
}

这是我的网络表单标记:

<asp:DataList ID="DataListAccount" runat="server" OnItemDataBound="DataList1_ItemDataBound1">
    <ItemTemplate>

        <tr>
            <td style="width: 171px">Account Status:</td>
            <td style="width: 220px">
                <asp:Label ID="lblAccountStatus" runat="server" Text='<%# Eval("ACCOUNT_STATUS") %>'></asp:Label>
            </td>
        </tr>
        <tr id="rowAccountName">
            <td style="width: 171px">Account Status:</td>
            <td style="width: 220px">
                <asp:Label ID="lblAccountName" runat="server" Text='<%# Eval("ACCOUNT_NAME") %>'></asp:Label>
            </td>
        </tr>

    </ItemTemplate>
</asp:DataList>

只需修改这段代码,添加多个条件

string value = Convert.ToString( row["MyColumn"]); 
if (string.IsNullOrEmpty(value))

您可以使用 PlaceHolder 包装 ItemTemplate 内容并使用三元运算符设置可见性。

<asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible='<%# !string.IsNullOrEmpty(Eval("ACCOUNT_STATUS").ToString()) ? true : false %>'>

    <tr>
        <td style="width: 171px">Account Status:</td>
        <td style="width: 220px">
            <asp:Label ID="lblAccountStatus" runat="server" Text='<%# Eval("ACCOUNT_STATUS") %>'></asp:Label>
        </td>
    </tr>       

</asp:PlaceHolder>

但我建议您确保过滤空项的源数据。像

SELECT * FROM accounts WHERE account_status IS NOT NULL