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" 

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <form id="form1" runat="server">
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:CodeCampSV06 %>" 
            "SELECT [Id], [Username], [Email] FROM [Attendees] ORDER BY [Id] DESC">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            DataKeyNames="Id" DataSourceID="SqlDataSource1" 
                <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" />