Code Button to Run Stored Procedure OnClick and Navigate to URL in ASP.NET

Visual Studio has a lot of great features when it comes to linking your awesome ASP.NET application items to a SQL Server database without a whole lot of code knowlege needed. That being said, there is a lot more that can be done in C# to make your application even more awesome (awesomer?).

For example, lets say you want to add a button object to your page that not only navigates to a new page (maybe a confirmation page or something?) but also runs a stored procedure against your database. You might be thinking, “Holy Moses, Ben. Only Mark Zuckerburg is capable of something like that.” Well, you’d be wrong because this can be done in a jiff using C#.

First, we make sure to load the proper assemblies. Add these to the begining of your .cs page.


Next, we add a public partial class in case we need to declare a parameter.

public partial class firstcount : System.Web.UI.Page
    DataSet ds = new DataSet();
    SqlConnection con;
    //Here we can declare a parameter
    SqlCommand cmd = new SqlCommand();

Now we define what we would like to happen when they hyperlink is clicked. In the scenario I have created, we want to pull the “ID” from the QueryString and use it in the Stored Procedure. You know, because thats what a truely awesome application would do.

protected void Button1_Click(object sender, EventArgs e)
        con = new SqlConnection("server=MySqlServer;
        cmd = new SqlCommand("MyStoredProcedure", con);
        cmd.CommandType = CommandType.StoredProcedure;
        Response.Redirect("NewPage.aspx?id=" +

Lastly, we add the ‘OnClick’ event to our button in our ASP.NET page.

<asp:Button ID="Button1" runat="server" Text="Complete" OnClick="Button1_Click" />

Thats it! What we have done is coded our button to run our stored procedure when it is clicked and then navigate the user to our confirmation page. Snazzy right? Its almost like we know what we are doing…

Now your users will be all like:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s