Chris Chris - 1 month ago 22
ASP.NET (C#) Question

How to display elements only if SQLDataSource has rows

I'm creating an ASP.NET/C# page where a user enters an ID at the top of the page, and when they press Submit, the page posts back and displays the data. Right now, the data fields are displayed at all times - even when the page loads and no search has taken place. This is not ideal as when they navigate a Menu with a MultiView I have made, some errors will come up. Plus it's obviously not good practise.

Is there a way I can hide all these elements (they are DetailsViews and GridViews, plus the MultiView and Menu) if the SQLDataSource is blank? So if the search returned nor esults, or no query has been executed yet.



You could surround these elements is a placeholder control and then set the placeholders visibility depending on whether there are result to display.
I haven't used the SqlDataSource object much before but to meet you requirements I would suggest checking to see if the page has been posted back in the PageLoad method and if not hiding the data controls. Then to handle the case of no results being returned adding a method to the SqlDataSource.Selected event:

<asp:PlaceHolder ID="myPlaceholder" runat="server">
     ....Data controlds

Code behind:

protected void Page_Load(object sender, EventArgs e)
        myPlaceholder.Visible = false;

protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
    myPlaceholder.Visible = e.AffectedRows > 0;