Accessing DropDownLists inside the GridView Control
By AzamSharp
Views: 25623

 

Introduction:

In this article I will demonstrate that how you can access the values of the DropDownList which resides in the GridView control. I will show you different ways in which you can extract the values out of the DropDownList and display it on the screen.

Adding DropDownList to the GridView Control:

Our first task is to add the DropDownList control to the GridView control. This can be done easily by using the Add New Column Dialog and adding a new template column. After adding a template column simply drag and drop a DropDownList inside the GridView control.

Populating the DropDownList inside the GridView Control:

In this article I will be using the Northwind database, Categories table. I will display Column CategoryName and the Description as the DropDownList columns. Let's see how we can populate the DropDownList controls. As you can see below that each of the method is used to fill a particular DropDownList.

public DataSet GetCategoryNames()

{

SqlConnection myConnection = new SqlConnection(ConnectionString);

SqlDataAdapter ad = new SqlDataAdapter("SELECT CategoryName FROM Categories", myConnection);

DataSet ds = new DataSet();

ad.Fill(ds, "Categories");

return ds;

}

public DataSet GetCategoryDescriptions()

{

SqlConnection myConnection = new SqlConnection(ConnectionString);

SqlDataAdapter ad = new SqlDataAdapter("SELECT Description FROM Categories", myConnection);

DataSet ds = new DataSet();

ad.Fill(ds, "Categories");

return ds;

}

 

Now we need to bind the DataSource property of the DropDownLists to the methods. This can be done using the HTML View of the page. I have also set the DataTextField and the DataValueField property of the DropDownList to the table columns.

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:TemplateField HeaderText="Category Name">
<ItemTemplate>
<asp:DropDownList DataSource='<%# GetCategoryNames() %>' DataTextField="CategoryName" DataValueField="CategoryName" ID="ddlCategoryName" runat="server">
</asp:DropDownList>

</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:DropDownList DataSource='<%# GetCategoryDescriptions() %>' DataTextField="Description" DataValueField="Description" ID="ddlDescription" runat="server">
</asp:DropDownList>

</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Select" ShowSelectButton="True" />
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
</asp:GridView>

Binding the DataSource to the GridView:

You also need to bind the DataSource of the GridView control. This is pretty much the same as we did for the DropDownList controls.

private void BindData()

{

SqlConnection myConnection = new SqlConnection(ConnectionString);

SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories", myConnection);

DataSet ds = new DataSet();

ad.Fill(ds, "Categories");

GridView1.DataSource = ds;

GridView1.DataBind();

}

Now if you run this code you will see the GridView with DropDownList columns which are populated.

Now we need to implement the code for the button click so that when we press the button we can get all the selected values in the DropDownLists. For clarity I have extracted the selected values from both the DropDownList and displayed it on another GridView control.

Button Click Code:

I have created a DataTable object which will hold the selected values of the DropDownList and bind it to another GridView control. All I did is created a GridViewRow instance which iterates through the GridView. GridViewRow uses its FindControl method to extract the values from the particular control. 

// Gets the selected items in the GridView Control

protected void Button1_Click(object sender, EventArgs e)

{

string categoryName = String.Empty;

string description = String.Empty;

DataTable dt = new DataTable();

dt.Columns.Add("CategoryName");

dt.Columns.Add("Description");

foreach (GridViewRow row in GridView1.Rows)

{

categoryName = ((DropDownList)row.FindControl("ddlCategoryName")).SelectedItem.Value;

description = ((DropDownList)row.FindControl("ddlDescription")).SelectedItem.Value;

DataRow dr = dt.NewRow();

dr["CategoryName"] = categoryName;

dr["Description"] = description;

dt.Rows.Add(dr);

}

GridView2.DataSource = dt;

GridView2.DataBind();

}

The result is given in the screen shot below:

Selecting Individual Rows:

The above procedure loops through the whole GridView control and extracts all the rows. If you need only a particular row then you can take advantage of the select column of the GridView. Simply add a select column in the GridView, now whenever you press the select column your selected row will be highlighted and thus activated. When you click on the select column the SelectedIndexChanged event is fired.

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)

{

string categoryName = ((DropDownList)GridView1.SelectedRow.FindControl("ddlCategoryName")).SelectedItem.Value;

Response.Write(categoryName);

}

 

The code above will simply prints the value from the CategoryName column on the screen.

I hope you liked the article, happy coding!

 

By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: Nice Code is this
Name: vikas
Date: 2/8/2007 12:54:56 AM
Comment:
Rocking Code. Its working very nice and gives very clear understanding of adding dropdownlist in gridview.

thanks
Subject: Editing clears drop down boxes
Name: Suresh Kumar
Date: 2/15/2007 6:28:11 AM
Comment:
Hi,

I added one drop down list box to disply some supplier names. When i Edit that record in the gridview, that column displays nothing and again if cancels that edit still it display nothing.

what is the problem i don't know?

Pls reply me. Thanx in Advance
Subject: gridview
Name: Achille
Date: 2/28/2007 9:08:40 PM
Comment:
I have try your code. It help me a lot to understand the gridview. but when I run the page the gridview doesn't show up. I put the GetCategoryNames(), GetCategoryDescriptions() and the BindData() methods after le page_load not inside. I try to bind the gridview normaly inside the page_load but nothing. the gridview refuse to show up. What can I do? thanks
Subject: Coding
Name: Cheyne
Date: 3/20/2007 6:02:17 AM
Comment:
Hi,

When ever I need info on Gridviews - I always try look for your examples ect. Step by step coding is GREAT!

Thank you
Subject: How to Update the Records?
Name: Sameer
Date: 4/11/2007 3:22:15 AM
Comment:
Azam,

I am unable to fire the RowUpdating event on the GridView. Any idea how to do this?
Subject: Feedback ( Great )
Name: Anil
Date: 4/11/2007 6:26:10 AM
Comment:
Really very great .
Subject: RE: Great
Name: AzamSharp
Date: 4/12/2007 1:05:23 PM
Comment:
Thanks Anil :)
Subject: good
Name: rajni
Date: 4/20/2007 3:33:54 AM
Comment:
I like this article.
Subject: grid and dropdownlist
Name: prerna
Date: 5/22/2007 10:16:13 PM
Comment:
This article is realy helpful to make grid cell changed into dropdown list.
Thanks
Subject: grid and dropdownlist
Name: prerna
Date: 5/22/2007 10:16:56 PM
Comment:
This article is realy helpful to make grid cell changed into dropdown list.
Thanks
Subject: Gridview
Name: Manpreet Singh
Date: 6/8/2007 2:41:28 AM
Comment:
Dear friend
I read the code that is good but I need the that code which fetch the code from the dropdownlist to gridview
thanking you
manpreet
Subject: good
Name: Giri
Date: 7/11/2007 5:35:22 AM
Comment:
Its nice and useful,but i have a doubt.If i want to add "SELECT" as the first item in dropdownlist what should i do?pls clarify this.
Subject: nice code
Name: ramesh
Date: 7/11/2007 11:40:37 PM
Comment:
thanks for giving such a good programming
Subject: Gridview
Name: Dave
Date: 10/4/2007 5:04:33 AM
Comment:
Hi,

Is there a way to add a dropdown list to a gridview object in code;

Not this:








This:
TemplateField tfield = new TemplateField();
...

thanks,
Dave
Subject: RE: Gridview
Name: AzamSharp
Date: 10/7/2007 9:18:59 AM
Comment:
Hi Dave,

For this you need to make the TemplateColumns dynamically. Check out the following article:

http://www.gridviewguy.com/ArticleDetails.aspx?articleID=88
Subject: Awesome!
Name: Mike
Date: 10/16/2007 2:22:03 PM
Comment:
This is a great piece of code! I am a gridviewguy for life!

Thanks,
Subject: SelectItem
Name: Sandeep
Date: 11/3/2007 3:28:31 PM
Comment:
I have DDLB that I populate using DataTable. It looks all good. Problem occurs when I click on the DDLB and change the selection, I cannot capture that changed selection the DDLB. The FindControl statement in the code still shows the old value..

Any ideas?

Thanks
Subject: Other Tutorials
Name: nadimo
Date: 11/3/2007 9:31:19 PM
Comment:
Very useful stuff.
Do you have a tutorial that explains how to use the input from the Select Button in the grid view to Update a detail view ? (prefer VB code).
Thanks .
Subject: GridView
Name: Vlad
Date: 12/13/2007 5:28:01 AM
Comment:
Great example!
Subject: very simple coding.I like it.
Name: Avinash
Date: 1/8/2008 11:44:01 PM
Comment:
Thank you very much...
Subject: How Can I Call these Methods in Page Load
Name: janardhan
Date: 3/12/2008 2:13:35 AM
Comment:
I have try your code. It help me a lot to understand the gridview. but when I run the page the gridview doesn't show up. I put the GetCategoryNames(), GetCategoryDescriptions() and the BindData() methods after le page_load not inside. I try to bind the gridview normaly inside the page_load but nothing. the gridview refuse to show up. What can I do?
Subject: need urgent help
Name: priyanka
Date: 3/13/2008 1:43:04 AM
Comment:
hi. helpful. but can u tell me how to populate my grid when i use a complex select query
Subject: Drop Down List
Name: charles hill
Date: 3/18/2008 4:25:52 PM
Comment:
I have a DropDownLis inside my gridview, and i want to handle the selected index changed event. do you know how i would do this?
Subject: RE: DropDownList
Name: AzamSharp
Date: 3/18/2008 9:15:25 PM
Comment:
Hi Charles Hill, Check out the following article: http://www.gridviewguy.com/ArticleDetails.aspx?articleID=169_DropDownList_Inside_GridView_(Meth and this: http://geekswithblogs.net/azamsharp/archive/2006/01/10/65433.aspx
Subject: Asp.net gridview(how to retrieve values of selected checkboxes in gridview)
Name: Dhiraj Jire
Date: 4/6/2008 9:17:46 PM
Comment:
i read some of document on this site which are really nice,and i want more information from you guys,how i can get that
Subject: Great, but...
Name: Robert
Date: 4/9/2008 2:48:07 PM
Comment:
This is great, but I need to populate the dropdown box with a list of hardcoded values instead of selecting the set from the database. How is this done?

-R
Subject: RE: Great, but...
Name: AzamSharp
Date: 4/9/2008 8:23:53 PM
Comment:
Hi Robert, If you want to populate it with the hardcoded values then simply switch to the HTML view add the ListItem inside the DropDownList control.
Subject: gridview
Name: babu
Date: 4/11/2008 12:33:16 AM
Comment:
hi,i am sendind no of comments but not getting any reply from u.so please help me i have one doubt.it's urgent.I have one gridview with dropdownlist control with different items.all different items are from database.that screenshot was there in your site.my problem is that selectitems from every dropdown in every rows and that value will be inserting to the another table.i am not getting the control of dropdoenlist.so plz help me how to get control by dynamically of dropdowlist.i need help it's very urgent.
Subject: Nice Code
Name: Aayush
Date: 5/2/2008 8:28:23 AM
Comment:
Nice code for gridview.



Join WebHost4Life.com






Copyright GridViewGuy 2007-2008