Skip to content

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

Updated: at 11:18 PM

The What and Where

Something that may not be obvious is if are creating an 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”>

<span class="kwrd">protected</span> <span class="kwrd">void</span> 
    GridView1_SelectedIndexChanged(<span class="kwrd">object</span> sender, EventArgs e)


<span class="kwrd">protected</span> <span class="kwrd">void</span> Page_Init(<span class="kwrd">object</span> sender, EventArgs e)
    <span class="kwrd">if</span> (!Context.User.Identity.IsAuthenticated)
        GridView1.Visible = <span class="kwrd">false</span>;


<html xmlns=“> <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>