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 days ago, a developer posts a comment in my previous article about “Adding Dynamic Rows in ASP.Net GridView Control with TextBoxes” asking if how to implement the same functionality with DropDownList.

In this example, I will going to show on how to generate a Row in GridView with DropDownList when clicking a Button that is residing inside a GridView Footer and retain the Selected Items of the DropDownList on postbacks.

Here are the code blocks below:

ASPX Source:

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

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

            <FooterStyle HorizontalAlign="Right" />

            <FooterTemplate>

             <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row"

                    onclick="ButtonAdd_Click" />

            </FooterTemplate>

        </asp:TemplateField>

        </Columns>

        </asp:gridview>

    </div>

    </form>

</body>

</html>

 

In the above declaration, I have set up some Template Fields columns so that GridView will automatically generate a row of DropDownLists when a new row is being added.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:

In this 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. 

    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;

 

        //Define the Columns

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

 

        //Add a Dummy Data on Initial Load

        dr = dt.NewRow();

        dr["RowNumber"] = 1;

        dt.Rows.Add(dr);

 

        //Store the DataTable in ViewState

        ViewState["CurrentTable"] = dt;

        //Bind the DataTable to the Grid

        Gridview1.DataSource = dt;

        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");

 

        FillDropDownList(ddl1);

        FillDropDownList(ddl2);

        FillDropDownList(ddl3);

 

    }

    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

                ViewState["CurrentTable"] = dtCurrentTable;

 

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

                {

                    //extract the DropDownList Selected Items

                    DropDownList ddl1 = (DropDownList)Gridview1.Rows[i].Cells[1].FindControl("DropDownList1");

                    DropDownList ddl2 = (DropDownList)Gridview1.Rows[i].Cells[2].FindControl("DropDownList2");

                    DropDownList ddl3 = (DropDownList)Gridview1.Rows[i].Cells[3].FindControl("DropDownList3");

 

                    // Update the DataRow with the DDL Selected Items

                    dtCurrentTable.Rows[i]["Column1"] = ddl1.SelectedItem.Text;

                    dtCurrentTable.Rows[i]["Column2"] = ddl2.SelectedItem.Text;

                    dtCurrentTable.Rows[i]["Column3"] = ddl3.SelectedItem.Text;

 

                }

 

                //Rebind the Grid with the current data

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

                {

                    //Set the Previous Selected Items on Each DropDownList on Postbacks

                    DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");

                    DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList2");

                    DropDownList ddl3 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList3");

 

                    //Fill the DropDownList with Data

                    FillDropDownList(ddl1);

                    FillDropDownList(ddl2);

                    FillDropDownList(ddl3);

 

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

                    {

                        ddl1.ClearSelection();

                        ddl1.Items.FindByText(dt.Rows[i]["Column1"].ToString()).Selected = true;

 

                        ddl2.ClearSelection();

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

 

                        ddl3.ClearSelection();

                        ddl3.Items.FindByText(dt.Rows[i]["Column3"].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 the 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! Hope you will find this example useful!

 

Posted on Tuesday, June 30, 2009 2:19 AM ASP.NET , C# , GridView | Back to top


Comments on this post: Adding Dynamic Rows in GridView with DropDownLists

# re: Adding Dynamic Rows in GridView with DropDownLists
Requesting Gravatar...
This is great post. But please how can i delete a row using delete button or checkbox template
Left by Paule on Aug 03, 2009 2:00 AM

# re: Adding Dynamic Rows in GridView with DropDownLists
Requesting Gravatar...
Thanks Vinz it worked for me. I recommend you write a book cos you are the best. infact you are the greatest
Left by Paule on Sep 01, 2009 4:01 AM

# re: Adding Dynamic Rows in GridView with DropDownLists
Requesting Gravatar...
i can't wait to read it! Please send ur email address
Left by Paule on Sep 01, 2009 6:46 PM

# re: Adding Dynamic Rows in GridView with DropDownLists
Requesting Gravatar...
did any one sucessful using Checkbox instead of dropdownlist.... Please help
Left by chetan on Jan 04, 2010 3:08 AM

# re: Adding Dynamic Rows in GridView with DropDownLists
Requesting Gravatar...
Thanks for the help.
Left by Piya on Jan 12, 2010 7:19 PM

# re: Adding Dynamic Rows in GridView with DropDownLists
Requesting Gravatar...
Can you plz tell me how to handle paging in this grid?

Thanks in advance
Leo
Left by Leo on Jan 22, 2010 1:20 PM

# re: Adding Dynamic Rows in GridView with DropDownLists
Requesting Gravatar...
Hi vinz,

have you tried a remove button link to this application?
Can you give me some tips, because I am having some error and it always turn or reset the value to -1 or says "Object reference not set to an instance of an object."
Left by Sunshine on Jun 11, 2010 2:01 PM

# re: Adding Dynamic Rows in GridView with DropDownLists
Requesting Gravatar...
hi Vins.. the value of DropdownList change when adding new row...is there anyway to keep the selected value unchange after adding new row..HELP PLEASE
and THANKS alot for the codes
Left by zorrs on Jun 04, 2011 4:39 PM

# re: Adding Dynamic Rows in GridView with DropDownLists(A Bit Urgent)
Requesting Gravatar...
when i delete the row from grid,drop down values are getting reset,Following is the code which i used for deleting
protected void RemoveButton_Click(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
int rowID = gvRow.RowIndex+1;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 1)
{
if (gvRow.RowIndex < dt.Rows.Count - 1)
{
//Remove the Selected Row data
dt.Rows.Remove(dt.Rows[rowID]);
}
}
//Store the current data in ViewState for future reference
ViewState["CurrentTable"] = dt;
//Re bind the GridView for the updated data
AdvanceSearchGridView.DataSource = dt;
AdvanceSearchGridView.DataBind();
}

//Set Previous Data on Postbacks

SetPreviousData();

}
i'll be pleased if i get some help..............!!!!!!!!!!!!!
Left by damodar on Nov 09, 2011 10:10 PM

comments powered by Disqus

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