Saturday, December 14, 2013

How to dynamically use SQLDataSource with GridView in ASP.Net and C#

SQLDataSource is a great tool which can be used with the famous GridView control to view and edit data with at ease. This tutorial is for those developers who wants to use these two powerful controls to build dynamic web application in a simple way.


TestPage2.aspx File

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestPage2.aspx.cs" EnableViewState="true" Inherits="Test.WebForm2" %>

<!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>
        <asp:Image ID="img" runat="server" ImageUrl="~/App_Data/restrict/indianvivah.jpg" />
        <asp:Image ID="Image1" runat="server" />

        <asp:GridView ID="gridView" runat="server"
            DataSourceID="sqlDataSource" DataKeyNames="testId"
            AutoGenerateEditButton="true"
            AutoGenerateDeleteButton="true">

        </asp:GridView>

        <asp:SqlDataSource ID="sqlDataSource" runat="server" />
    </div>
    </form>
</body>

</html>



TestPage2.aspx.cs  File

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Web.Configuration;

namespace Test
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            int testid=0;

            if (Request.QueryString["testid"] != null)
            {
                testid=Convert.ToInt16(Request.QueryString["testid"]);
            }

            PopulateGridView(testid);
        }

        public void PopulateGridView(int testid)
        {
            //Getting the connection string from web.config file
sqlDataSource.ConnectionString = WebConfigurationManager.ConnectionStrings["conStr"].ToString();

//Selecting dynamic query for the sqlDataSource and later the extracted   //resultset will be displayed on the GridView. Interesting fact is we don't //need to use GridView.DataBind() method.
            //SQLDataSource control will take care that internally.
            if (testid == 0)
            {
                sqlDataSource.SelectCommand = "Select * from test";
            }
            else
            {
sqlDataSource.SelectCommand = "Select * from test where testid=" + testid;
            }

//Update statement. Here the Primary key of the table is testId and that has //been mentioned as
            //DataKeyNames="testId" in the GridView control on .aspx page.
sqlDataSource.UpdateCommand = "Update test set name=@name, address=@address where testId=@testId";

            //Delete statement.
            sqlDataSource.DeleteCommand = "Delete test where testId=@testId";

        }
    }

}