简体   繁体   中英

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

I need to hide table rows in a DataList if column data returns null from SQL Server (for each individual column). I have it working successfully but this method will be very tedious as I have about 100 rows in my table. Surely there is a simpler way.

Here is my C# code:

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;
    }
}

Here is my webform markup:

<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>

You can wrap the ItemTemplate contents with a PlaceHolder and use a Ternary Operator to set the visibility.

<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>

But I would recommend you make sure you filter the source data of empty items. Something like

SELECT * FROM accounts WHERE account_status IS NOT NULL

just modify this code by adding multiple conditions

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM