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.
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 = newSqlConnection(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();
}
}
No comments:
Post a Comment