The SelectCommand property has not been initialized before calling 'Fill' Gridview error solution in | Bind Gridview from sql server database

Introduction: In this article I will explain the following with example:
  • How to solve the error “The SelectCommand property has not been initialized before calling 'Fill'.”
  • How to bind / load/ fill gridview with sql server database in using both C# and VB.Net language.
Bind gridView from sql server example in

Reason and Solution: In previous gridview related articles i explained with example How to  Bind,Save,Edit,Update,Cancel,Delete,Paging example in GridView in C# and Bind and Export GridView data to PDF file in and How to upload, download and delete files from GridView and How to bind gridview and highlight gridview row on mouse over.
 The above error usually occurs if you missed to initialize the SelectCommand property.

So the solution is to write the following code to bind gridview:

SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd
SqlDataAdapter adp = new SqlDataAdapter(cmd);

Note: Read the full article for the complete working code to bind the gridview without any error.

ImplementationLet's create an application to bind gridview from sql server database.
  • First Create the database in sql server e.g. Emp_DB and in this create a table with the following structure and give name Emp_Tb
Column Name
Data Type
Int(primary key so set Is Identity= Yes

  •  In the web.config file create the connection string to connect our application with sql server database.
    <add name="conStr" connectionString="Data Source=LocalServer;Initial Catalog=Emp_DB;Integrated Security=True"/>

HTML Source:

  • Place a GridView control from the Data category of the visual studio’s toolbox.

<fieldset style="width:345px;">
    <legend>Bind GridView example in</legend>
    <asp:GridView ID="grdEmp" runat="server" AutoGenerateColumns="False"
            CellPadding="4" ForeColor="#333333" GridLines="None">
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
         <HeaderStyle CssClass="fixedHeader" BackColor="#5D7B9D" Font-Bold="True"
                ForeColor="White" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <asp:TemplateField HeaderText="Emp Name">              
                    <asp:Label ID="lblEmpName" runat="server" Text='<%# Bind("EmpName") %>'></asp:Label>
            <asp:TemplateField HeaderText="Address">              
                    <asp:Label ID="lblAddress" runat="server" Text='<%# Bind("Address") %>'></asp:Label>
            <asp:TemplateField HeaderText="DOJ">            
                    <asp:Label ID="lblDOJ" runat="server" Text='<%# Bind("DOJ") %>'></asp:Label>
            <asp:TemplateField HeaderText="Salary">              
                    <asp:Label ID="lblSalary" runat="server" Text='<%# Bind("Salary") %>'></asp:Label>
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />

C#.Net Code
  • In the code behind file(.aspx.cs) write the code as:
First include the following namespaces

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

Then write the code to bind the gridview on page load event:

   SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
        if (!Page.IsPostBack)
    private void BindEmpGrid()
        DataSet ds = new DataSet();
        SqlDataAdapter adp = new SqlDataAdapter();
            SqlCommand cmd = new SqlCommand("select *  from Emp_Tb", con);
            adp.SelectCommand = cmd;

            if (ds.Tables[0].Rows.Count > 0)
                grdEmp.DataSource = ds;
        catch (Exception ex)
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);

VB.Net Code
  • In the code behind file(.aspx.vb) write the code as:
First import the following namespaces

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

Then write the code to bind the gridview on page load event:

  Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
        End If
    End Sub

    Private Sub BindEmpGrid()
        Dim ds As New DataSet()
        Dim adp As New SqlDataAdapter()
            Dim cmd As New SqlCommand("select *  from Emp_Tb", con)
            adp.SelectCommand = cmd

            If ds.Tables(0).Rows.Count > 0 Then
                grdEmp.DataSource = ds
            End If
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
        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 for more technical updates."
Next Post »

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..