Yesterday, I received an email from a user who wanted to know how to add multiple rows to the GridView control. This means that you can add any number of rows using the "Add" button and the rows will append at the end of the GridView control.
Let's first populate the GridView control.
private void BindData()
{
NorthwindDataContext northwind = new NorthwindDataContext();
gvReport.DataSource = GetProducts();
gvReport.DataBind();
}
private List<Product> GetProducts()
{
NorthwindDataContext northwind = new NorthwindDataContext();
return (from p in northwind.Products
select p).Take(3).ToList<Product>();
}
The GridView also contains a DropDownList so let's also populate the DropDownList.
protected List<Category> GetCategories()
{
NorthwindDataContext northwind = new NorthwindDataContext();
return northwind.Categories.ToList<Category>();
}
Here it the ASPX code for the GridView control:
<asp:GridView ID="gvReport" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="ProductName">
<ItemTemplate>
<%# Eval("ProductName") %>
<asp:TextBox ID="txtProductName" runat="server" Visible='<%# DoesProductExists( (string) Eval("ProductName")) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CategoryID">
<ItemTemplate>
<asp:DropDownList ID="ddlCategories" DataSource=<%# GetCategories() %> DataTextField="CategoryName" DataValueField="id" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
As, you can see I also have a TextBox control inside the ItemTemplate of the GridView control. This is to allow the user to add text when the new row is created. The TextBox will only be displayed if the row does not contain any data.
protected bool DoesProductExists(string productName)
{
if (String.IsNullOrEmpty(productName)) return true;
return false;
}
Now, let's say I click on the "Add" button then the following event is fired.
// adds the new row
protected void Button1_Click(object sender, EventArgs e)
{
Count += 1;
var list = GetProducts();
// add empty elements at the end of the list
list.AddRange(new Product[Count]);
gvReport.DataSource = list;
gvReport.DataBind();
}
Count is a ViewState property as shown below:
public int Count
{
get
{
if (ViewState["Count"] == null)
return 0;
return (int) ViewState["Count"];
}
set
{
ViewState["Count"] = value;
}
}
The Count property determines how many rows to append to the GridView control. I have also used the UpdatePanel to make the effect Postbackless :).
Here is the animation of the effect:
