With ASP.NET WebForms, How to Keep / Stop a Data Control Like GridView From Retrieving Data

Posted by Peter Kellner on August 01, 2011 · 3 mins read

The What and Where

Something that may not be obvious is if are creating an asp.net WebForms project and you put a datasource such as SqlDataSource or ObjectDataSource for example on the page, how can you prevent the SqlSelect associated with that datasource from being triggered.

The answer is to set the control’s visible property to false.  That’s it!

 

The Why

The reason you might want to do this is for a case where you have a public facing web page that might be easily subjected to a denial of service attach.  If that web page is always causing some SqlDataSource to fire, you could easily find your SqlServer overloaded.  At least by checking to see a user is logged in before firing the sql statement, you buy yourself a little bit of protection.

 

The Code

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected void 
        GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    protected void Page_Init(object sender, EventArgs e)
    {
        if (!Context.User.Identity.IsAuthenticated)
        {
            GridView1.Visible = false;
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:CodeCampSV06 %>" 
            SelectCommand=
            "SELECT [Id], [Username], [Email] FROM [Attendees] ORDER BY [Id] DESC">
            </asp:SqlDataSource>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            DataKeyNames="Id" DataSourceID="SqlDataSource1" 
            onselectedindexchanged="GridView1_SelectedIndexChanged">
            <Columns>
                <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" 
                    ReadOnly="True" SortExpression="Id" />
                <asp:BoundField DataField="Username" HeaderText="Username" 
                    SortExpression="Username" />
                <asp:BoundField DataField="Email" HeaderText="Email" 
                SortExpression="Email" />
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>