Here i have created a sample in which i am adding the Department Listbox items to DataTable. Rows are added in DataTable with the items of Department ListBox. After that Listbox 2 which is Incharge ListBox is added in DataTable according to rows count of DataTable. Its because if the Incharge ListBox is having more number of items then it will give the error like index out of range error.
HTML:
<form id="form1" runat="server">
<div>
<asp:ListBox ID="lbDepartment" runat="server">
<asp:ListItem Text="HR" />
<asp:ListItem Text="Accounts" />
<asp:ListItem Text="IT" />
<asp:ListItem Text="Reception" />
</asp:ListBox>
<br />
<asp:ListBox ID="lbIncharge" runat="server">
<asp:ListItem Text="Ram" />
<asp:ListItem Text="Ram" />
<asp:ListItem Text="Raj" />
<asp:ListItem Text="Suresh" />
<asp:ListItem Text="Raj" />
<asp:ListItem Text="Suresh" />
</asp:ListBox>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("Department", typeof(string));
dt.Columns.Add("Incharge", typeof(string));
for (int i = 0; i < this.lbDepartment.Items.Count; i++)
{
DataRow dr = dt.NewRow();
dr["Department"] = this.lbDepartment.Items[i].Text;
dt.Rows.InsertAt(dr, i);
}
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i]["Incharge"] = this.lbIncharge.Items[i].Text;
}
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
}
Image:
Thank You.