In this article I will explain with an example, how to generate dynamic Rows in
GridView with DropDownList in
ASP.Net using C# and VB.Net.
HTML Markup
The HTML Markup consists of following controls:
GridView – For displaying data.
The GridView consists of one BoundField column and three TemplateField columns.
TemplateField
The TemplateField column consists of ItemTemplate which consists of DropDownList and FooterTemplate consists of Button.
DropDownList
Each DropDownList consists of one ListItem.
<asp:GridView ID="GridView1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 1">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:DropDownList ID="DropDownList3" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Add New Row" OnClick="OnAdd" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Namespaces
You will need to import the following namespace.
C#
VB.Net
Bind DataTable to GridView
Inside the Page_Load event handler, the SetInitialRow method is called.
SetInitialRow
Inside the SetInitialRow method, the DataTable is store inside the ViewState and DataTable is assigned with the DataSource property of the GridView.
Then, DropDownList class object is created it extract and fill the data.
Finally, the PopulateDropDownList method is called where we pass DropDownList class object as parameter.
PopulateDropDownList
Inside the PopulateDropDownList method, new ListItem are created with its values.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.SetInitialRow();
}
}
private void SetInitialRow()
{
//Store the DataTable in ViewState.
ViewState["CurrentTable"] = this.CurrentTable;
GridView1.DataSource = this.CurrentTable;
GridView1.DataBind();
//Extract and Fill the DropDownList with Data.
DropDownList ddl1 = (DropDownList)GridView1.Rows[0].Cells[1].FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)GridView1.Rows[0].Cells[2].FindControl("DropDownList2");
DropDownList ddl3 = (DropDownList)GridView1.Rows[0].Cells[3].FindControl("DropDownList3");
//Fill the DropDownList with Data.
this.PopulateDropDownList(ddl1);
this.PopulateDropDownList(ddl2);
this.PopulateDropDownList(ddl3);
}
private void PopulateDropDownList(DropDownListddl)
{
ddl.Items.Add(new ListItem("Item1", "1"));
ddl.Items.Add(new ListItem("Item2", "2"));
ddl.Items.Add(new ListItem("Item3", "3"));
ddl.Items.Add(new ListItem("Item4", "4"));
ddl.Items.Add(new ListItem("Item5", "5"));
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.SetInitialRow()
End If
End Sub
Private Sub SetInitialRow()
'Store the DataTable in ViewState.
ViewState("CurrentTable") = Me.CurrentTable
GridView1.DataSource = Me.CurrentTable
GridView1.DataBind()
'Extract and Fill the DropDownList with Data.
Dim ddl1 As DropDownList = CType(GridView1.Rows(0).Cells(1).FindControl("DropDownList1"), DropDownList)
Dim ddl2 As DropDownList = CType(GridView1.Rows(0).Cells(2).FindControl("DropDownList2"), DropDownList)
Dim ddl3 As DropDownList = CType(GridView1.Rows(0).Cells(3).FindControl("DropDownList3"), DropDownList)
'Fill the DropDownList with Data.
Me.PopulateDropDownList(ddl1)
Me.PopulateDropDownList(ddl2)
Me.PopulateDropDownList(ddl3)
End Sub
Private Sub PopulateDropDownList(ByVal ddl As DropDownList)
ddl.Items.Add(New ListItem("Item1", "1"))
ddl.Items.Add(New ListItem("Item2", "2"))
ddl.Items.Add(New ListItem("Item3", "3"))
ddl.Items.Add(New ListItem("Item4", "4"))
ddl.Items.Add(New ListItem("Item5",, "5"))
End Sub
Adding Dynamic Rows with DropDownList
OnAdd
When the Add button is clicked, the AddNewRowtoGrid method is called.
AddNewRowtoGrid
Inside the AddNewRowtoGrid method, the check is performed if the DataTable is not null.
Then, DataTable and DataRow class object is created and again the check is performed if DataTable row count is greater than 0.
The FOR EACH loop is executed and then it Extract and Update the DataRow with the DropDownList Selected Items.
Then, again the DataTable is assigned with DataSource property of the GridView.
If not then it displays the message in
JavaScript alert message box.
Finally, the SetPreviousData method is called.
CurrentTable
Inside the CurrentTable method, get and set method is called.
Inside get method, the check is performed if the ViewState is not null then, it returns DataTable if not then, it can create DataTable and DataRow class object and return the DataTable.
Inside set method, ViewState is set with the value.
SetPreviousData
Inside the SetPreviousData method, the check is performed if the DataTable not equal to NULL.
Then, the DataTable class object is created again check is performed if count greater than 0.
The FOR EACH loop is executed and the DropDownList values are set.
Then, the PopulateDropDownList method is called and data is filled.
Again check is performed if the DropDownList items not equal to null then, it clear the selection and set DropDownList item to TRUE.
C#
protected void OnAdd(object sender, EventArgs e)
{
this.AddNewRowToGrid();
}
private void AddNewRowToGrid()
{
if (this.CurrentTable != null)
{
DataTable dtCurrentTable = this.CurrentTable;
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
int i = 1;
foreach (GridViewRow row in GridView1.Rows)
{
//Extract the DropDownList Selected Items.
DropDownList ddl1 = (DropDownList)row.FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)row.FindControl("DropDownList2");
DropDownList ddl3 = (DropDownList)row.FindControl("DropDownList3");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
//Update the DataRow with the DropDownList Selected Items.
dtCurrentTable.Rows[i -1]["Column1"] = ddl1.SelectedItem.Text;
dtCurrentTable.Rows[i -1]["Column2"] = ddl2.SelectedItem.Text;
dtCurrentTable.Rows[i -1]["Column3"] = ddl3.SelectedItem.Text;
i++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
this.CurrentTable = dtCurrentTable;
//Rebind the Grid with current data.
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('ViewState is null.');", true);
}
//Set Previous Data on PostBack.
this.SetPreviousData();
}
private DataTable CurrentTable
{
get
{
if (ViewState["CurrentTable"] != null)
{
return (DataTable)ViewState["CurrentTable"];
}
else
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
DataRow dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dt.Rows.Add(dr);
return dt;
}
}
set
{
ViewState["CurrentTable"] = value;
}
}
private void SetPreviousData()
{
int i = 0;
if (this.CurrentTable != null)
{
DataTable dt = this.CurrentTable;
if (dt.Rows.Count > 0)
{
foreach (GridViewRow row in GridView1.Rows)
{
DropDownList ddl1 = (DropDownList)row.FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)row.FindControl("DropDownList2");
DropDownList ddl3 = (DropDownList)row.FindControl("DropDownList3");
//Fill the DropDownList with Data.
this.PopulateDropDownList(ddl1);
this.PopulateDropDownList(ddl2);
this.PopulateDropDownList(ddl3);
if (ddl1.Items.FindByText(dt.Rows[i]["Column1"].ToString()) != null)
{
ddl1.ClearSelection();
ddl1.Items.FindByText(dt.Rows[i]["Column1"].ToString()).Selected = true;
}
if (ddl2.Items.FindByText(dt.Rows[i]["Column1"].ToString()) != null)
{
ddl2.ClearSelection();
ddl2.Items.FindByText(dt.Rows[i]["Column2"].ToString()).Selected = true;
}
if (ddl3.Items.FindByText(dt.Rows[i]["Column1"].ToString()) != null)
{
ddl3.ClearSelection();
ddl3.Items.FindByText(dt.Rows[i]["Column3"].ToString()).Selected = true;
}
i++;
}
}
}
}
VB.Net
Protected Sub OnAdd(ByVal sender As Object, ByVal e As EventArgs)
Me.AddNewRowToGrid()
End Sub
Private Sub AddNewRowToGrid()
If Me.CurrentTable IsNot Nothing Then
Dim dtCurrentTable As DataTable = Me.CurrentTable
Dim drCurrentRow As DataRow = Nothing
If dtCurrentTable.Rows.Count > 0 Then
Dim i As Integer = 1
For Each row As GridViewRow In GridView1.Rows
'Extract the DropDownList Selected Items.
Dim ddl1 As DropDownList = CType(row.FindControl("DropDownList1"), DropDownList)
Dim ddl2 As DropDownList = CType(row.FindControl("DropDownList2"), DropDownList)
Dim ddl3 As DropDownList = CType(row.FindControl("DropDownList3"), DropDownList)
drCurrentRow = dtCurrentTable.NewRow()
drCurrentRow("RowNumber") = i + 1
'Update the DataRow with the DropDownList Selected Items.
dtCurrentTable.Rows(i -1)("Column1") = ddl1.SelectedItem.Text
dtCurrentTable.Rows(i -1)("Column2") = ddl2.SelectedItem.Text
dtCurrentTable.Rows(i -1)("Column3") = ddl3.SelectedItem.Text
i += 1
Next
dtCurrentTable.Rows.Add(drCurrentRow)
Me.CurrentTable = dtCurrentTable
'Rebind the Grid with current data.
GridView1.DataSource = dtCurrentTable
GridView1.DataBind()
End If
Else
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert(' ViewState is null.');", True)
End If
'Set Previous Data on PostBack.
Me.SetPreviousData()
End Sub
Private Property CurrentTable As DataTable
Get
If ViewState("CurrentTable") IsNot Nothing Then
Return CType(ViewState("CurrentTable"), DataTable)
Else
Dim dt As DataTable = New DataTable()
dt.Columns.Add(New DataColumn("RowNumber", GetType(String)))
dt.Columns.Add(New DataColumn("Column1", GetType(String)))
dt.Columns.Add(New DataColumn("Column2", GetType(String)))
dt.Columns.Add(New DataColumn("Column3", GetType(String)))
Dim dr As DataRow = dt.NewRow()
dr("RowNumber") = 1
dr("Column1") = String.Empty
dr("Column2") = String.Empty
dr("Column3") = String.Empty
dt.Rows.Add(dr)
Return dt
End If
End Get
Set(ByVal value As DataTable)
ViewState("CurrentTable") = value
End Set
End Property
Private Sub SetPreviousData()
Dim i As Integer = 0
If Me.CurrentTable IsNot Nothing Then
Dim dt As DataTable = Me.CurrentTable
If dt.Rows.Count > 0 Then
For Each row As GridViewRow In GridView1.Rows
Dim ddl1 As DropDownList = CType(row.FindControl("DropDownList1"), DropDownList)
Dim ddl2 As DropDownList = CType(row.FindControl("DropDownList2"), DropDownList)
Dim ddl3 As DropDownList = CType(row.FindControl("DropDownList3"), DropDownList)
'Fill the DropDownList with Data.
Me.PopulateDropDownList(ddl1)
Me.PopulateDropDownList(ddl2)
Me.PopulateDropDownList(ddl3)
If ddl1.Items.FindByText(dt.Rows(i)("Column1").ToString()) IsNot Nothing Then
ddl1.ClearSelection()
ddl1.Items.FindByText(dt.Rows(i)("Column1").ToString()).Selected = True
End If
If ddl2.Items.FindByText(dt.Rows(i)("Column1").ToString()) IsNot Nothing Then
ddl2.ClearSelection()
ddl2.Items.FindByText(dt.Rows(i)("Column2").ToString()).Selected = True
End If
If ddl3.Items.FindByText(dt.Rows(i)("Column1").ToString()) IsNot Nothing Then
ddl3.ClearSelection()
ddl3.Items.FindByText(dt.Rows(i)("Column3").ToString()).Selected = True
End If
i += 1
Next
End If
End If
End Sub
Screenshot
Downloads