Hi,
Here is the solution for your question:
Create 2 table in sql server
1-> Table for Department named tblDepartment habing fields a)DeptId int
b)DeptName nvarchar(30)
2->Table for employees named tblEmployes having fields a)id int,
b)EmployeeId nvarchar(30),
c)DeptId int,
D)Employee Name etc add field name as per your requirement.
Note: What ever the value of DeptId in tblDepartment should be same for DeptId in tblEmployes values.
ASPX code:
<pre><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlDepartment" runat="server" AutoPostBack="True"
onselectedindexchanged="ddlDepartment_SelectedIndexChanged">
</asp:DropDownList>
<asp:GridView ID="gvEmployes" runat="server" AutoGenerateColumns="false">
</asp:GridView>
</div>
</form>
</body>
</html>
Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString.ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDepartmentIds();
}
}
private void BindDepartmentIds()
{
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from tblDepartment",con);
DataSet dsDepartment = new DataSet();
da.Fill(dsDepartment);
ddlDepartment.DataTextField = "DeptId";
ddlDepartment.SelectedValue = "DeptId";
ddlDepartment.DataSource = dsDepartment;
ddlDepartment.DataBind();
}
catch { }
finally { con.Close(); }
}
protected void ddlDepartment_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("Select * from tblEmployes where deptid='"+ddlDepartment.SelectedValue.ToString()+"'",con);
DataSet dsEmployees = new DataSet();
da.Fill(dsEmployees);
gvEmployes.DataSource = dsEmployees;
gvEmployes.DataBind();
}
catch { }
finally { con.Close(); }
}
}