Adding Multiple Rows in the GridView Control
By AzamSharp
Views: 19454

Introduction:

A while back an article was published on www.gridviewguy.com which explained how to add a single row at the bottom of the GridView control. You can read the article using this link. Many readers were interested in the idea of adding multiple rows to the GridView. This article explains how to add multiple rows to the GridView control.

Populating the GridView Control:

The first task is to populate the GridView control. We will be using the LINQ to SQL Classes to populate the GridView but you can use any data container that you like.

private void BindData()
        {
            NorthwindDataContext northwind = new NorthwindDataContext();
            gvReport.DataSource = GetProducts();
            gvReport.DataBind();
        }

        // since the product list is long I am only selecting three products
        private List<Product> GetProducts()
        {
            NorthwindDataContext northwind = new NorthwindDataContext();
            return (from p in northwind.Products
                    select p).Take(3).ToList<Product>();
        }

The database is the Northwind database and we are using the Products table of the database. The GetProducts method returns the top three products from the Products table (You can return all the rows it does not really matter).

Here is the ASPX part of the code:

<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>

The first column displays the “ProductName”. If the ProductName is not available then a TextBox is created which is used to enter a new ProductName.

The GetCategories method is used to populate the DropDownList in the second column of the GridView control. Here is the implementation of the GetCategories method.

  protected List<Category> GetCategories()
        {
            NorthwindDataContext northwind = new NorthwindDataContext();
            return northwind.Categories.ToList<Category>();
        }


Adding New Rows to the GridView Control:

Now, let’s see how to add new rows to the GridView control. The rows are added using the “Add” Button control. Here is the implementation of the add button click.

// 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();
        }

Let’s first talk about how we are going to add empty rows to the GridView control. Each time a button is clicked the postback is triggered. So, we need a way to know how many empty rows have to be created. We will use ViewState to store the number of rows that have to be created and then add the rows in the product list as empty products.

The Count property in the button click code is used to store the number of empty rows to be created. Here is the implementation of the Count property.

public int Count
        {
            get
            {
                if (ViewState["Count"] == null)
                    return 0;

                return (int) ViewState["Count"];
            }
            set
            {
               
                ViewState["Count"] = value;
            }
        }

The list.AddRange(new Product[Count]); line is used to append the rows to the product list.

The effect is shown in the GIF Animation below:


I have also used UpdatePanel to eliminate the server postback.

I hope you liked the article, happy coding!

 

 

By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: GIF Animation
Name: Danny
Date: 2/7/2008 10:42:50 AM
Comment:
How did you make the GIF animation? That is really cool and would be very useful.
Subject: RE: GIF Animation
Name: AzamSharp
Date: 2/7/2008 11:03:30 AM
Comment:
Hi Danny, I used Camtasia.
Subject: Hii
Name: Cathy
Date: 2/8/2008 1:43:45 PM
Comment:
very useful article :)..but could u explain what exatly is NorthwindDataContext northwind = new NorthwindDataContext();
and how does it relate to dataAdapter and dataset..because i can't see any da,ds in ur example..Plz explain that..

Thanks,
Cathy
Subject: RE: Hii
Name: AzamSharp
Date: 2/9/2008 9:08:44 AM
Comment:
Hi, I am using LINQ to SQL Classes but you can use DataSet or DataTable.
Subject: grid view
Name: anuj
Date: 2/24/2008 8:38:11 AM
Comment:
great coding
Subject: Adding Multiple Rows in the GridView Control
Name: shankar
Date: 3/2/2008 10:59:44 PM
Comment:
sir,
i used the same code,namespaces and dlls, what you given in this article. but iam getting Error 'Linq' does not exist in the namespace 'System.Xml'
please suggest me.
Subject: RE: Adding Multiple Rows
Name: AzamSharp
Date: 3/4/2008 10:16:15 PM
Comment:
Hi Shankar, The code will run on the 3.5 framework using LINQ. If you are using 3.5 framework then make a reference to System.Data.Linq.
Subject: RE: Adding Multiple Rows
Name: Vikram Pendse
Date: 3/8/2008 1:48:05 AM
Comment:
Hi..Its a good article! ..I tried such adding of row using session by this code snippet
Dim dt As DataTable
Session("grid") = dt
Dim l As Integer = 0
For Each row As GridViewRow In GridViewDx.Rows
Session("grid").Rows(l).Item("Diagnosis") = CType(row.FindControl("txtName"), TextBox).Text
....
l = l + 1
Next

Dim i As Integer
i = Session("grid").Rows.Count
drblank1 = Session("grid").NewRow
Session("grid").Rows.InsertAt(drblank1, i + 1)

but your code seems to be very smooth..will it work for normal project which are not implementing LINQ, Also would like to know do we have "AND" and "OR" operators while writing LINQ queries,especially while doing LINQ to Objects/Collections. I am very new to LINQ..so asking this questions.

Thanks
Vikram Pendse.
Subject: code
Name: Parthasarathy Mandayam
Date: 3/11/2008 11:24:52 AM
Comment:
Do you have the source code for this?
What's the 2+2 question for?
Subject: hi
Name: kumar velu
Date: 3/18/2008 9:41:16 PM
Comment:
do you know how use dataset here instead of NorthwindDataContext.... pls help .. thanks in advance!
Subject: Trainee
Name: Partha Barata Ghosh
Date: 3/19/2008 3:23:47 AM
Comment:
fine code
Subject: Article
Name: Dale
Date: 3/25/2008 8:27:22 AM
Comment:
I get a compilation error stating that the name 'DoesProductExists' does not exist in the current context.If at all possible could you please explain why I'm getting this error. Thank You
Subject: Article
Name: Dale
Date: 3/25/2008 11:18:04 AM
Comment:
Do you have any code for the btnUpdate click event?
Thank you?
Subject: RE: Article
Name: AzamSharp
Date: 3/25/2008 12:28:31 PM
Comment:
Hi Dale, Please download the attached files and I am sure you will find out the implementation of the DoesProductExists method.
Subject: prefect
Name: Brian
Date: 3/28/2008 8:56:48 AM
Comment:
very useful for me!
thank you!i will come back a lot.
Subject: math
Name: susanta
Date: 4/2/2008 5:37:37 AM
Comment:
i m agree with u
Subject: GridView Add New
Name: menon
Date: 4/10/2008 3:30:12 AM
Comment:
Hi There, I am using RequiredFieldValidator for the TextBox. Sometimes It works, but sometimes it gives me Javascript Error ControlToValidate is null. I see the ClientID of the TextBox Changes dynamically hence it loses the value of ControlToValidate. Can you please help me.

Thanks

Menon
Subject: Nice Article
Name: Nitin Kumar
Date: 4/25/2008 12:36:59 AM
Comment:
It was nice article but could not help me out
Subject: Source code
Name: MrBaby
Date: 5/21/2008 10:26:07 PM
Comment:
Could you give me full source code, please?.

Thank first.
Subject: RE: Source Code
Name: AzamSharp
Date: 5/22/2008 4:48:56 PM
Comment:
Hi MrBaby, The source code is attached at the end of the article.
Subject: Not Getting DoesProductExists
Name: Md. Golam Rabbani
Date: 6/17/2008 12:48:12 AM
Comment:
i am not getting the 'DoesProductExists' method....Will u please give me the implementation of that method
Subject: re: not getting DoesProductExists
Name: AzamSharp
Date: 6/18/2008 8:01:47 AM
Comment:
You can download the code using the following url:

http://gridviewguy.com/ArticleDownloads/GridViewAddingMultipleRows.zip




Join WebHost4Life.com






Copyright GridViewGuy 2007-2008