Please disable your adblock and script blockers to view this page
 

How to bind gridview using SqlDataAdapter, DataSet and query in Asp.net

Gridview Binding example in asp.net
Click on image to enlarge
IntroductionIn previous articles i explained How to pass parameter to stored procedure using SqlDataAdapter and check login in asp.net and How to bind gridview using SqlDataAdapter, SqlCommand, DataTable and Stored procedure in Asp.net and How to bind gridview using SqlDataAdapter, DataTable and query in Asp.net. There are a number of ways to bind data with GridView control in asp.net. In this article i have explained how to bind GridView using SqlDataAdapter, DataSet and inline query in Asp.net


  •  Create a Database e.g. "MyDataBase" and a table under that DataBase in Sql Server and name it "EMPLOYEE" as  shown in figure:
Binding gridview example in asp.net
Click on image to enlarge

 Note: EMP_ID column is set to Primary key and Identity specification is set to yes with Identity increment and Identity seed equal to 1. Insert some data in this table that you  want to show in the Gridview.
  • Now in web.config file add the  connection string under <configuration> tag :
<connectionStrings>
    <add name="EmpCon" connectionString="Data Source=LocalServer;Initial Catalog=MyDataBase;Integrated Security=True"/>
  </connectionStrings>


Note: Replace the Data Source and the Initial catalog as per your application.
  • Add a GridView control in design page of your asp.net website under <BODY> tag
<fieldset style="width:230px;">
            <legend>Gridview Binding Example</legend>
            <asp:GridView ID="EmpGridView" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">    
         <AlternatingRowStyle BackColor="White" />
       <Columns>  
        <asp:BoundField DataField="EMP_NAME"  HeaderText="Name" />
        <asp:BoundField DataField="DEPT"  HeaderText="Department" />
        <asp:BoundField DataField="SALARY"  HeaderText="Salary" />  
      </Columns>
         <EditRowStyle BackColor="#2461BF" />
         <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
         <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
         <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
         <RowStyle BackColor="#EFF3FB" />
         <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
         <SortedAscendingCellStyle BackColor="#F5F7FB" />
         <SortedAscendingHeaderStyle BackColor="#6D95E1" />
         <SortedDescendingCellStyle BackColor="#E9EBEF" />
         <SortedDescendingHeaderStyle BackColor="#4870BE" />
 </asp:GridView>
        </fieldset>
  • In the code behind file(.aspx.cs)  of your asp.net website write the code as:

C#.Net Code to bind gridview using SqlDataAdapter, DataSet and query in Asp.net

First include the following namespaces

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
 
then write code as:
  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindEmpGrid();
        }      
    }

    private void BindEmpGrid()
    {
        DataSet ds = new DataSet();
        try
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EmpCon"].ConnectionString);
           
            SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM EMPLOYEE", con);
         
            adp.Fill(ds);

            if (ds.Tables[0].Rows.Count > 0)
            {
                EmpGridView.DataSource = ds;
                EmpGridView.DataBind();
            }
            else
            {
                EmpGridView.DataSource=null;
                EmpGridView.DataBind();
            } 
        }
        catch(Exception ex)
        {
            Response.Write("Error Occured: " + ex.ToString());
        }
        finally
        {
            ds.Clear();
            ds.Dispose();
        }
    }

 VB.Net Code to bind gridview using SqlDataAdapter, DataSet and query in Asp.net

First import the following namespaces

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

then write code as:


Private Sub BindEmpGrid()
                    Dim ds As New DataSet()
                    Try
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("EmpCon").ConnectionString)

                                         Dim adp As New SqlDataAdapter("SELECT * FROM EMPLOYEE", con)

                                         adp.Fill(ds)

                                         If ds.Tables(0).Rows.Count > 0 Then
                                                             EmpGridView.DataSource = ds
                                                             EmpGridView.DataBind()
                                         Else
                                                             EmpGridView.DataSource = Nothing
                                                             EmpGridView.DataBind() 
                                         End If
                    Catch ex As Exception
                                         Response.Write("Error Occured: " & ex.ToString())
                    Finally
                                         ds.Clear()
                                         ds.Dispose()
                    End Try

End Sub

Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."
Previous
Next Post »

2 comments

Click here for comments
Anonymous
admin
September 27, 2013 ×

Dear sir
This is piyush sharma. I need a help regarding the gridview when we click on the gridview row the value will be displayed on the popup window in the gridview pl tell me if it is possible its urgent

Reply
avatar
September 27, 2013 ×

Hello piyush..i got your requirement and yes it is possible..i will create an article as per your requirement as soon as possible..so keep reading for more useful updates :)

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily.. ConversionConversion EmoticonEmoticon