Here is a way to implement the task
First of all create 2 tables namely Employee and Department with a foreign key relation.
Employee table should contain the following columns ID(primary key), FirstName, LastName, DeptID(which is a foreign key)
Department table should contain the following columns DeptID(Primary key) and DepartmentName
Insert some data to the two tables as per our requirement, my sample data in the tables is as follows
Now as per our requirement I would like to show the department names on the Tabs. I used AJAX TabContainer
Place a panel initially on the web form so that you design should be as follows
Your code should be like as follows
As I created an SqlDatabase file I have my connection string in web.config is as follows
<connectionStrings>
</connectionStrings>
You can change the connectionstring as per your requirement.
public partial class dynamicTab : System.Web.UI.Page
{
string strCon = ConfigurationManager.ConnectionStrings["SqlCon"].ConnectionString.ToString();
TabContainer ajxTab;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// createTab();
SqlConnection con = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand("select DeptID,DepartmentName from Department", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Table tblDynamic = new Table();
TableRow tbrDynamic = new TableRow();
TableCell tbcDynamic = new TableCell();
GridView grdDyanmic = new GridView();
grdDyanmic.AutoGenerateColumns = true;
SqlCommand cmd1 = new SqlCommand("select * from Employee where DeptID='" + ds.Tables[0].Rows[i]["DeptID"].ToString() + "'", con);
SqlDataAdapter da1 = new SqlDataAdapter();
DataSet ds1 = new DataSet();
da1.SelectCommand = cmd1;
da1.Fill(ds1);
grdDyanmic.DataSource = ds1;
grdDyanmic.DataBind();
tbcDynamic.Controls.Add(grdDyanmic);
tbrDynamic.Cells.Add(tbcDynamic);
tblDynamic.Rows.Add(tbrDynamic);
ajxTab.Tabs[i].Controls.Add(tblDynamic);
}
pnlDynamic.Controls.Add(ajxTab);
}
}
protected void page_init(object sender, EventArgs e)
{
createTab();
}
private void createTab()
{
SqlConnection con = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand("select DeptID,DepartmentName from Department", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
ajxTab = new AjaxControlToolkit.TabContainer();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
TabPanel tbpnlDynamic = new TabPanel();
tbpnlDynamic.HeaderText = ds.Tables[0].Rows[i]["DepartmentName"].ToString();
tbpnlDynamic.ID = ds.Tables[0].Rows[i]["DeptID"].ToString(); // Here I am assigning DeptID to the TabPanel so that it will be easy to retrieve the data what we needed from database
ajxTab.Tabs.Add(tbpnlDynamic);
ajxTab.ActiveTabIndex = 0;
}
}
}
Hope you enjoyed the article, if any questions or queries please let me know.
Any comments welcome..