Query Strings in ASP.NET


Introduction


Before talking about anything else, first of all let's look at both terms query and strings.

What are query and strings?

Actually, query poses a question or say it is an instance of questioning. Whatever a user of a search engine or database enters is sometimes called the query. A database query can be either a select query or an action query. A select query is simply a data retrieval query. An action query can ask for additional operations on the data, such as insertion, updating, or deletion. String is sequence of characters, either as a literal constant or as some kind of variable.

So, query string may be called as "a question or instance of questioning asked using strings".

ASP.NET Query Strings

Query String is a way to pass data or travel data between pages via URL. Sometimes, we can see URL something like http://www.google.com/search?q=itorian , have ever tried to understand that?

In above URL, http://www.google.com/search is normal web URL but after a question mark (?), we can see "q" and its value equal to "itorian'.

What are "q" and "itorian"?

q is similar to a variable and itorian is its value and both sections, normal url section and query sections are separated by and question (?) mark.

Can we pass many variables?

Yes, using Query Strings we can pass multiple variables as well. Look at the example.

http://www.google.com/search?q=itorian&hl=en

In above example, now we have two different variables separated by & (and) sign, first variable is "q" and second is "hl".

What is the use of all these stuffs?

The main use of this stuff is to pass or travel data from one page to another and these data can be used for any work like for some calculations or some database queries. Mostly, query strings are used for to establish database query.

Now, all the basics we have covered so far but not practical's, let's do this too.

Scenario of Practical

We are going to find result of any student from database using query strings. For, this we need to have some project pages and a sample database. Let's look at them one by one.

Database Structure

I have created following database in my project, look at screenshot.
 

Default.aspx

This page has just a textbox and a button having a click event.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <b>Pleas enter your roll number to find result:</b>
    <br /><br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <br /><br />
        <asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click1"/>
    </div>
    </form>
</body>
</html>

Default.aspx.cs

This code has just a Response.Redirect statement inside button click event. Response.Redirect will pass the value using query string.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }

    protected void Button1_Click1(object sender, EventArgs e)
    {
        Response.Redirect(String.Format("Result.aspx?Roll=",TextBox1.Text));
    }
}

Result.aspx

This page has just a DataGrid and its data will be bind from its page_load.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Result.aspx.cs" Inherits="Result" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <b>Your Result</b>
        <br /><br />
        <asp:GridView ID="GridView1" runat="server" BackColor="White"
            BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4"
            GridLines="Horizontal">
            <FooterStyle BackColor="White" ForeColor="#333333" />
            <HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="White" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F7F7F7" />
            <SortedAscendingHeaderStyle BackColor="#487575" />
            <SortedDescendingCellStyle BackColor="#E5E5E5" />
            <SortedDescendingHeaderStyle BackColor="#275353" />
        </asp:GridView>
       
    </div>
    </form>
</body>
</html>

Result.aspx.cs

This page has a query string receiver Request.QueryString["Roll"] which will receive the value from URL and will be used in sql query.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Configuration;
using System.Data.SqlClient;
public partial class Result : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["Roll"] != null)
        {
            string rollnumber = Request.QueryString["Roll"];

            string connectionString = WebConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString;
            string selectSQL = "SELECT * FROM Table1 WHERE roll='" + rollnumber + "'";
            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand(selectSQL, con);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();

            adapter.Fill(ds, "Result");

            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
    }
}

Configuration

Web.config files has a connection string, as given below.

<?xml version="1.0"?>
<configuration>
       <connectionStrings>
              <add name="DatabaseConnectionString1" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
       </connectionStrings>
       <system.web>
              <compilation debug="true" targetFramework="4.0"/>
       </system.web>
</configuration>

So, that's all about the query string and its uses. Similarly, we can use query string for passing multiple values.

Comments

Popular posts from this blog

Customize User's Profile in ASP.NET Identity System

Migrating database from ASP.NET Identity to ASP.NET Core Identity