Geeks With Blogs

News

Microsoft MVP


DZone MVB


Moderator at CodeASP.NET


Quiz Master







free counters
Free counters
Added on January 19,2012


Follow Me @vmsdurano

A bit About Me



Disclaimer
The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.


Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

Few months ago I wrote a sample demo on how to Add Dynamic Rows in GridView with TextBoxes and how to Add Dynamic Rows in GridView with DropDownLists.  I have had a few comments and emails asking how to do the same with a combination of TextBox and DropDownList. In this post, I'm going to show you the way on how to this.

Here are the code blocks below:

ASPX:  

<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:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Header 2">
            <ItemTemplate>
                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField  HeaderText="Header 3">
            <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 4">
            <ItemTemplate>
                <asp:DropDownList ID="DropDownList2" runat="server"
                                  AppendDataBoundItems="true">
                     <asp:ListItem Value="-1">Select</asp:ListItem>
                </asp:DropDownList>
            </ItemTemplate>
            <FooterStyle HorizontalAlign="Right" />
            <FooterTemplate>
                 <asp:Button ID="ButtonAdd" runat="server" 
                             Text="Add New Row" 
                             onclick="ButtonAdd_Click" />
            </FooterTemplate>
        </asp:TemplateField>
        </Columns>
</asp:gridview> 

As you can see from the markup above, I have set up a BoundField for displaying the RowNumber and some Template Field columns so that GridView will automatically generate a row of TextBox and DropDownLists when adding a new row.You will also notice that I have added a Button Control under the FooterTemplate at the last column in the GridView.

Note: Since we are added a Control in the GridView footer, then be sure to set ShowFooter to TRUE in the GridView.

CODE BEHIND:

Again, just like in my previous example,We are going to populate the DropDownLists on the fly. Note that I am using a dummy data and stored it in the ArrayList just for the simplicity of this demo. 

public partial class GridDemo : System.Web.UI.Page 
{ 
        private ArrayList GetDummyData() { 

            ArrayList arr = new ArrayList(); 

            arr.Add(new ListItem("Item1", "1")); 
            arr.Add(new ListItem("Item2", "2")); 
            arr.Add(new ListItem("Item3", "3")); 
            arr.Add(new ListItem("Item4", "4")); 
            arr.Add(new ListItem("Item5", "5")); 

            return arr; 
        } 

        private void FillDropDownList(DropDownList ddl) { 
            ArrayList arr = GetDummyData(); 

            foreach (ListItem item in arr) { 
                ddl.Items.Add(item); 
            } 
        } 

        private void SetInitialRow() { 

            DataTable dt = new DataTable(); 
            DataRow dr = null; 

            dt.Columns.Add(new DataColumn("RowNumber", typeof(string))); 
            dt.Columns.Add(new DataColumn("Column1", typeof(string)));//for TextBox value 
            dt.Columns.Add(new DataColumn("Column2", typeof(string)));//for TextBox value 
            dt.Columns.Add(new DataColumn("Column3", typeof(string)));//for DropDownList selected item 
            dt.Columns.Add(new DataColumn("Column4", typeof(string)));//for DropDownList selected item 

            dr = dt.NewRow(); 
            dr["RowNumber"] = 1; 
            dr["Column1"] = string.Empty; 
            dr["Column2"] = string.Empty; 
            dt.Rows.Add(dr); 

            //Store the DataTable in ViewState for future reference 

            ViewState["CurrentTable"] = dt; 

            //Bind the Gridview 
            Gridview1.DataSource = dt; 
            Gridview1.DataBind(); 

           //After binding the gridview, we can then extract and fill the DropDownList with Data 

            DropDownList ddl1 = (DropDownList)Gridview1.Rows[0].Cells[3].FindControl("DropDownList1"); 
            DropDownList ddl2 = (DropDownList)Gridview1.Rows[0].Cells[4].FindControl("DropDownList2"); 
            FillDropDownList(ddl1); 
            FillDropDownList(ddl2); 
        } 

        private void AddNewRowToGrid() { 

            if (ViewState["CurrentTable"] != null) { 

                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"]; 
                DataRow drCurrentRow = null; 

                if (dtCurrentTable.Rows.Count > 0) { 
                    drCurrentRow = dtCurrentTable.NewRow(); 
                    drCurrentRow["RowNumber"] = dtCurrentTable.Rows.Count + 1; 

                    //add new row to DataTable 
                    dtCurrentTable.Rows.Add(drCurrentRow); 
                    //Store the current data to ViewState for future reference 

                    ViewState["CurrentTable"] = dtCurrentTable; 


                    for (int i = 0; i < dtCurrentTable.Rows.Count - 1; i++) { 

                        //extract the TextBox values 

                        TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1"); 
                        TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2"); 

                        dtCurrentTable.Rows[i]["Column1"] = box1.Text; 
                        dtCurrentTable.Rows[i]["Column2"] = box2.Text; 

                       //extract the DropDownList Selected Items 

                        DropDownList ddl1 = (DropDownList)Gridview1.Rows[i].Cells[3].FindControl("DropDownList1"); 
                        DropDownList ddl2 = (DropDownList)Gridview1.Rows[i].Cells[4].FindControl("DropDownList2"); 

                        // Update the DataRow with the DDL Selected Items 

                        dtCurrentTable.Rows[i]["Column3"] = ddl1.SelectedItem.Text; 
                        dtCurrentTable.Rows[i]["Column4"] = ddl2.SelectedItem.Text; 

                    } 

                    //Rebind the Grid with the current data to reflect changes 
                    Gridview1.DataSource = dtCurrentTable; 
                    Gridview1.DataBind(); 
                } 
            } 
            else { 
                Response.Write("ViewState is null"); 

            } 
            //Set Previous Data on Postbacks 
            SetPreviousData(); 
        } 

        private void SetPreviousData() { 

            int rowIndex = 0; 
            if (ViewState["CurrentTable"] != null) { 

                DataTable dt = (DataTable)ViewState["CurrentTable"]; 
                if (dt.Rows.Count > 0) { 

                    for (int i = 0; i < dt.Rows.Count; i++) { 

                        TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1"); 
                        TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2"); 

                        DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1"); 
                        DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[4].FindControl("DropDownList2"); 

                        //Fill the DropDownList with Data 
                        FillDropDownList(ddl1); 
                        FillDropDownList(ddl2); 

                        if (i < dt.Rows.Count - 1) { 

                           //Assign the value from DataTable to the TextBox 
                            box1.Text = dt.Rows[i]["Column1"].ToString(); 
                            box2.Text = dt.Rows[i]["Column2"].ToString(); 

                            //Set the Previous Selected Items on Each DropDownList  on Postbacks 
                            ddl1.ClearSelection(); 
                            ddl1.Items.FindByText(dt.Rows[i]["Column3"].ToString()).Selected = true; 

                            ddl2.ClearSelection(); 
                            ddl2.Items.FindByText(dt.Rows[i]["Column4"].ToString()).Selected = true; 

                        } 

                        rowIndex++; 
                    } 
                } 
            } 
        } 

        protected void Page_Load(object sender, EventArgs e) { 
            if (!Page.IsPostBack) { 
                SetInitialRow(); 
            } 
        } 

        protected void ButtonAdd_Click(object sender, EventArgs e) { 
            AddNewRowToGrid(); 
        } 
}

Method Definitions:

GetDummyData()

A method that returns an ArrayList. Basically this method contains a static dummy data for populating the DropDownList.

FillDropDownList(DropDownList ddl)

A method that fills the DropDownList with the dummy data.

SetInitialRow()

A method that binds the GridView on initial load with a single row of data. The DataTable defined in this method is stored in ViewState so that it can be referenced anywhere in the codes when it postbacks. Basically this table will serve as the original DataSource for the GridView.

AddNewRowToGrid()

A method that adds a new row to the GridView when a Button is clicked and store the newly added row values in the Original Table that was defined in the SetInitialRow() method.

SetPreviousData()

A method that retains all the items that was selected from the DropDownList when it postbacks.


The output would look something like below when you run it on the browser:

On Initial Load:

 

After Adding some Rows:

 

That's it! I hope someone find this useful.

 

Posted on Tuesday, August 3, 2010 2:41 PM ASP.NET , GridView | Back to top


Comments on this post: Adding Dynamic Rows in GridView with TextBox and DropDownList

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
Wow i was looking only for this through out the web.Could you tell me how we can put a Delete button on each row to remove desired newly created Dynamic set of controls.
Thank you in advance.
Left by Xitij Thool on Jan 11, 2011 7:47 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
I already presented an example about it some time ago here:
http://geekswithblogs.net/dotNETvinz/dotNETvinz/dotNETvinz/archive/2009/08/09/adding-dynamic-rows-in-asp.net-gridview-control-with-textboxes-and.aspx
Left by Vinz on Jan 11, 2011 10:30 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
i tried u r application. its really helps me out.

but i have to bind more than one row to that gridview

when ever i bind thw rows more than 1 row its give me index out of bound exception
Left by vaibhav on Feb 09, 2011 7:22 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
Thnx Vinz for such a neat and clean code, this help me a lot, thnx once again
Left by Joe on Feb 27, 2011 5:38 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
Thanks a lot. I wanted exactly this functionality.
Left by Mushfiq on Mar 20, 2011 12:39 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
Nice helped me very much
Left by Rajib Bhowmik on Mar 24, 2011 5:15 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
is there any way to bind data in to that combo box
Left by zorrs on Jun 03, 2011 12:55 AM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
@zorrs,

Yes. Instead of using the GetDummyData() method above.. You can create a method that returns a DataTable/List. In that method you can query your database and fill your DataTable/List with the result set. Check this link for example: http://geekswithblogs.net/dotNETvinz/archive/2009/02/24/binding-dropdownlist-listbox-and-checkboxlist-control-the-ado.net-way.aspx
Left by Vinz on Jun 03, 2011 3:48 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
thanks...but i tried and fail....what i want is to bind data to dynamic dropdownlist....from the grid...
when working with the code it gives error...that is tha dropDownList inside the grid is not showing in the code...
i hope you understand my question...
Please help
Left by zorrs on Jun 04, 2011 4:21 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
@zorrs.

I really wanted to help you on this matter but I am tied up with deadlines. If you want to get more help from developers then I'd suggest you to post your issue at the forums: http://forums.asp.net/
Left by Vinz on Jun 06, 2011 1:54 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
Great example, it helped me achieve what I was trying to do. I do have a question as to what would be the best way to retrieve the data entered in the event that it needed to be updated?
Left by Rocky on Aug 02, 2011 11:32 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
how can i add Calendar control in this gridview to be used in web application??
thank you in advance..
Left by Aravindh on Aug 12, 2011 5:51 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
Thank u so much,
I have changed littile bit,It's working
Left by rashmi on Aug 19, 2011 11:22 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
It help me lotssss...but i hv one problem when i edit this records in another form then rows are added but in previous data is not shown.....
Left by Sunil on Sep 10, 2011 2:32 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
i m fresher in a software company. from my point of view this code is very useful .
thanks for submit the code online.
Left by Naved on Sep 20, 2011 12:12 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
Hi, very nice , but instead of creating dummy data to dropdownlist, why can't we bind data from database to dropdownlist.. please tel me the code for " how to binddata to dropdown list from sqlserver database , while creating dynamic rows"
Left by kishore on Dec 30, 2011 12:35 AM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
@kishore,

Check this post: http://geekswithblogs.net/dotNETvinz/archive/2009/02/24/binding-dropdownlist-listbox-and-checkboxlist-control-the-ado.net-way.aspx
Left by VInz on Dec 30, 2011 1:03 AM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
can we do same in client side.

Thanks in advance.
Left by vilas on Feb 21, 2012 2:13 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
Do not initialize the GridView SetInitialRow function () if you are within a FromView not understand why?
Left by C Torres on Feb 28, 2012 3:19 AM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
Awesome!!! Please also show the code for how delete the row dynamically...
Left by Naresh on Mar 02, 2012 6:01 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
@Naresh,

Please see this artcile:

http://geekswithblogs.net/dotNETvinz/dotNETvinz/archive/2009/08/12/updated-adding-dynamic-rows-in-asp.net-gridview-control-with-textboxes-again.aspx
Left by Vinz on Mar 02, 2012 6:07 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
Thank's friend!
Left by Juan ALberto on Mar 05, 2012 7:52 AM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
Thanks for the code. It worked like a charm.
I have a different requirement though.
I should be able to add new rows to the grid having data.
Earlier rows should be displayed as labels and newly added ones as textboxes. Any help would be greatly appreciated.
Left by Swaru on Mar 06, 2012 3:44 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
Hi, very nice artical.It help me lot.
Left by SUKANTA SAHA on Mar 10, 2012 3:51 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
nice example helps lot
Left by V Patel on May 09, 2012 2:33 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
Thanks much!
Left by Aaron on May 30, 2012 9:39 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
Great code!
I am implementing with a 'dual' grid setup and checkboxlist.
Basically, if they check the checkbox, the grid is enabled and they can select/add multiple sets of data (kind of a sample request scenario).
Aside from the additional gridview and juggling the two possibilities in the ViewState it's working great with one exception: I can do one or two items, but when I try to add a third row, the codebehind (specifically:
dtCurrentTable.Rows[i]["Column3"] = ddl1.SelectedItem.Text; )
isn't returning a selectedItem. It HAS a dropdown that it found - it just doesn't show anything as being selected.
Now the one thing I am doing is that, since these are bound to the selection (enable/disable(clear)) of a checkbox - I have this in an updatePanel to enable or disable with only partial page postbacks.
I can include some code if needed but I've been staring at this and trying to add dynamic ASyncPostbacks on the "add" button(s) and all sorts of things but it just seems like it doesn't recognize that anything is selected in the dynamically added dropdown.
Any ideas? if there's anything additional to take into consideration with an UpdatePanel around the gridview?

Left by Michael on Jun 22, 2012 4:13 AM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
when i am using this code foe muliple gridview on the same page i m getting an error on the second grid view that index out of range please help provide me the code when two or more gridview are implemented with the same fuctionality of adding row dynamically
Left by Anurag on Jun 24, 2012 6:17 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
@Anurag,
Are you using a single viewstate to hold both your gridviews? Sounds like you are, possibly. With multiple gridviews you'll need to store the data for each in a seperate viewstate object. IE: ViewState("table1") - ViewState("table2").
Left by Michael on Jun 26, 2012 11:52 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
AAARRGH!
I converted to VB and misplaced the rebind INSIDE the AddNewRow loop!
DOH!

Just thought I'd pass that along in case anyone else does the same stupid thing. :-)
Left by Michael on Jul 06, 2012 11:07 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
Hi,

The code works fine with out paging,but

I'm having a problem when trying to add a new row to a grid view when the grid view paging is "2" for example. Basically, when the data I'm trying to add will be on page number two of the grid, the drop down list I'm trying to bind raises an exception saying that the index is out of range.

private void SetPreviousData() {

int rowIndex = 0;
if (ViewState["CurrentTable"] != null) {

DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0) {

for (int i = 0; i < dt.Rows.Count; i++) {

TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");
//code is getting failed at this point
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells

How can I add a new grid row with paging and how to tell the drop down list that the row it is looking for is no longer 3, but 1 on the second page?

Any help will be greatly appreciated.

Left by shakuntala on Aug 02, 2012 7:00 PM

# re: Adding Dynamic Rows in GridView with TextBox and DropDownList
Requesting Gravatar...
thanks alot.. it helps in solving my issue
Left by vamsirays on Dec 01, 2012 11:18 AM

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: GeeksWithBlogs.net