How to Get DropDownList selected value and Fill details in GridView and labels based on that in asp.net

Introduction: In this article I am going to explain with example How to get DropDownList selected value/item and based on that value fetch the detailed data and show/display in GridView and Label/TextBox controls in asp.net using C#.Net and VB.Net languages.

Description: So basically you will learn the following through this article:
  • How to Bind/ Load/ Fill DropDownList from Sql server database table.
  • How to Get DropDownList selected value and based on that fetch details of that record and show in GridView and Label Controls.
  • How to Bind/Load /Fill Gridview Data Control with data from sql server. 

Get DropDownList selected value and Fill details in GridView and labels based on that in asp.net

Implementation: In previous related articles i explained How to Fill Country,State,Cities in the DropDownList and Bind,Save,Edit,Update,Cancel,Delete,Paging example in GridView and  Fill CheckBoxList based on DropDownList selection and Ajax CascadingDropDown example in asp.net to Fill DropDownList with Countries,states and cities and Example to Validate DropDownList using jQuery in asp.net. Now let's create an asp.net application to understand.

 First of all create the database in Sql Server e.g. “Emp_Db” and in that create a table with the fields as shown below and name it “Emp_Tb”.


Column
Data Type
Emp_Id
Int(Primary key so set Is Identity=True)
EmpName
varchar(100)
City
varchar(100)
Salary
int

  •  In the web.config create the connection string to connect the asp.net application with the sql server database as:
<connectionStrings>
    <add name="conStr" connectionString="Data Source=Lalit-Pc;Initial Catalog=Emp_DB;Integrated Security=True"/>
  </connectionStrings>
  
Note: Change the Data Source=Lalit-Pc as per yours.

Source Code:
  • In the <Form> Tag of the design page (.aspx) place a DropDownList control, A GridView control and Four Labels and set their properties as shown below
<div>
<fieldset style="width:320px;">
    <legend>DropDownList selected value details in GridView</legend>
    <table>
    <tr><td>Select Emp Id: </td><td>
        <asp:DropDownList ID="ddlEmpRecord" runat="server" AutoPostBack="True"
            onselectedindexchanged="ddlEmpRecord_SelectedIndexChanged" Height="18px"
            Width="121px" CausesValidation="True">
        </asp:DropDownList><br />
        <asp:CompareValidator ID="CompareValidator1" runat="server"
            ControlToValidate="ddlEmpRecord" Display="Dynamic"
            ErrorMessage="Please select Emp id" ForeColor="Red" Operator="NotEqual"
            SetFocusOnError="True" ValueToCompare="-- Select --"></asp:CompareValidator>
        </td></tr>

    <tr><td colspan="2">
    <asp:GridView ID="grdEmp" runat="server" AutoGenerateColumns="false">
        <Columns>
        <asp:BoundField HeaderText="Emp Id" DataField="Emp_Id" />
        <asp:BoundField HeaderText="Emp Name" DataField="EmpName" />
        <asp:BoundField HeaderText="City" DataField="City" />
        <asp:BoundField HeaderText="Salary" DataField="Salary" />
        </Columns>
        </asp:GridView></td></tr>
    <tr><td colspan="2"></td></tr>
    </table>
     <asp:Label ID="lblEmpId" runat="server" Text=""></asp:Label><br />
     <asp:Label ID="lblEmpName" runat="server" Text=""></asp:Label><br />
     <asp:Label ID="lblCity" runat="server" Text=""></asp:Label><br />
     <asp:Label ID="lblSalary" runat="server" Text=""></asp:Label>
    </fieldset>
    </div>

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;

and write the code as:

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            FillEmpDropdownList();        
        }
    }

    protected void FillEmpDropdownList()
    {
        SqlCommand cmd = new SqlCommand();
        SqlDataAdapter adp = new SqlDataAdapter();
        DataTable dt = new DataTable();
        try
        {
            cmd = new SqlCommand("Select * from Emp_Tb", con);       
            adp.SelectCommand=cmd;           
            adp.Fill(dt);
            ddlEmpRecord.DataSource = dt;
            ddlEmpRecord.DataTextField = "Emp_Id";
            ddlEmpRecord.DataValueField = "Emp_Id";
            ddlEmpRecord.DataBind();
            ddlEmpRecord.Items.Insert(0, "-- Select --");
            //OR    ddlEmpRecord.Items.Insert(0, new ListItem("Select Emp Id", "-1"));
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
        }
        finally
        {           
            cmd.Dispose();           
            adp.Dispose();
            dt.Clear();
            dt.Dispose();           
        }        
    }
    protected void ddlEmpRecord_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            int empId = Convert.ToInt32(ddlEmpRecord.SelectedValue);
            BindEmpGrid(empId);
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
        }       
    }

    private void BindEmpGrid(Int32 empId)
    {
        DataTable dt = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter();
        try
        {
            SqlCommand cmd = new SqlCommand("select *  from Emp_Tb where Emp_Id=" + empId + " ", con);
            adp.SelectCommand = cmd;
            adp.Fill(dt);

            if (dt.Rows.Count > 0)
            {
               grdEmp.DataSource = dt;
               lblEmpId.Text = "Emp Id :" +  dt.Rows[0]["Emp_Id"].ToString();
               lblEmpName.Text ="Emp Name: " + dt.Rows[0]["EmpName"].ToString();
               lblCity.Text = "City: " +dt.Rows[0]["City"].ToString();
               lblSalary.Text = "Salary: " + dt.Rows[0]["Salary"].ToString();
               grdEmp.DataBind();
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
        }
        finally
        {
            dt.Clear();
            dt.Dispose();
            adp.Dispose();
        }
    }


VB.Net Code
  • Design the page as shown in Source Code above but replace the line
         <asp:DropDownList ID="ddlEmpRecord" runat="server" AutoPostBack="True"
            onselectedindexchanged="ddlEmpRecord_SelectedIndexChanged" Height="18px"
            Width="121px" CausesValidation="True">
        </asp:DropDownList>
With    
     <asp:DropDownList ID="ddlEmpRecord" runat="server" AutoPostBack="True" Height="18px"
            Width="121px" CausesValidation="True">
        </asp:DropDownList>

  •  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 as:
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
            FillEmpDropdownList()
        End If
    End Sub

    Protected Sub FillEmpDropdownList()
        Dim cmd As New SqlCommand()
        Dim adp As New SqlDataAdapter()
        Dim dt As New DataTable()
        Try
            cmd = New SqlCommand("Select * from Emp_Tb", con)
            adp.SelectCommand = cmd
            adp.Fill(dt)
            ddlEmpRecord.DataSource = dt
            ddlEmpRecord.DataTextField = "Emp_Id"
            ddlEmpRecord.DataValueField = "Emp_Id"
            ddlEmpRecord.DataBind()
            'OR    ddlEmpRecord.Items.Insert(0, new ListItem("Select Emp Id", "-1"));
            ddlEmpRecord.Items.Insert(0, "-- Select --")
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
        Finally
            cmd.Dispose()
            adp.Dispose()
            dt.Clear()
            dt.Dispose()
        End Try
    End Sub

    Protected Sub ddlEmpRecord_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles ddlEmpRecord.SelectedIndexChanged
        Try
            Dim empId As Integer = Convert.ToInt32(ddlEmpRecord.SelectedValue)
            BindEmpGrid(empId)
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
        End Try
    End Sub

    Private Sub BindEmpGrid(empId As Int32)
        Dim dt As New DataTable()
        Dim adp As New SqlDataAdapter()
        Try
            Dim cmd As New SqlCommand("select *  from Emp_Tb where Emp_Id=" & Convert.ToString(empId) & " ", con)
            adp.SelectCommand = cmd
            adp.Fill(dt)

            If dt.Rows.Count > 0 Then
                grdEmp.DataSource = dt
                lblEmpId.Text = "Emp Id :" & dt.Rows(0)("Emp_Id").ToString()
                lblEmpName.Text = "Emp Name: " & dt.Rows(0)("EmpName").ToString()
                lblCity.Text = "City: " & dt.Rows(0)("City").ToString()
                lblSalary.Text = "Salary: " & dt.Rows(0)("Salary").ToString()
                grdEmp.DataBind()
            End If
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
        Finally
            dt.Clear()
            dt.Dispose()
            adp.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 for more technical updates."
Previous
Next Post »

7 comments

Click here for comments
Simon
admin
October 02, 2013 ×

Thank you very much for this nice tutorial.

Reply
avatar
October 03, 2013 ×

Thanks Simon for appreciating my tutorial website..stay connected and keep reading..:)

Reply
avatar
Anonymous
admin
December 03, 2013 ×

Nice tutorial tnx............

Reply
avatar
December 03, 2013 ×

Your welcome..keep reading and stay tuned for more updates :)

Reply
avatar
February 08, 2014 ×

Hi arun..i am glad your found this article useful for you..thanks for reading and sharing your feedback..:)

Reply
avatar
Sadaa
admin
May 08, 2014 ×

Nice post... Thanks...

Reply
avatar
May 08, 2014 ×

Thanks sadanand sonar for your feedback..it is always nice to hear that my articles helped anyone..keep reading and stay connected..

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