DropDownList Inside GridView (Method 1)
By AzamSharp
Views: 57550

Introduction:

In one of my previous articles I explained that how you can embed a DropDownList inside the GridView control. You can check out the article at Accessing DropDownList inside the GridView Control. If you look closely you will notice that all the DropDownList inside the GridView contains the same information. In this article I will demonstrate that how you can have DropDownList inside the GridView exposing different information.

Analysis:

There are couple of ways in which you can achieve this task. In this article I will demonstrate the approach of using DataSet to populate the DropDownList inside the GridView. Take a look at the screen shot below so, you will have a clear idea of what you will be learning in this article.

As, you can see in the above image that each DropDownList is different and is populated on the basis of the category type. Now, let's see the code.

The first thing that you need to do is to populate the GridView so that it will have CategoryID and CategoryName. These are the first two columns of the GridView.

private DataSet GetDataSet()

{

string query = @"SELECT p.CategoryID,p.ProductID, p.ProductName FROM Products p

SELECT c.CategoryID,c.CategoryName FROM Categories c";

string connectionString = @"Server=localhost;Database=Northwind;Trusted_Connection=true";

SqlConnection myConnection = new SqlConnection(connectionString);

SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);

DataSet ds = new DataSet();

ad.Fill(ds);

return ds;

}

Since, the query consists of two SELECT statements it means that it will return two tables. The table that I am interested in is the Table[1] which contains the result of (SELECT c.CategoryID,c.CategoryName FROM Categories c"). In the Page_Load event you can bind the DataTable to the GridView using the code below: 

protected void Page_Load(object sender, EventArgs e)

{

if (!Page.IsPostBack)

{

// This is because Table[1] contains Categories

GridView1.DataSource = GetDataSet().Tables[1];

GridView1.DataBind();

}

}

If you run your application now then you will see that your GridView consists of the CategoryID and CategoryName columns but no GridView column. Keep in mind that CategoryID and CategoryName are bound columns.

Add a simple template column to the GridView and place a DropDownList inside the template column. Here is the HTML code for the GridView control.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">

<Columns>

<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />

<asp:BoundField DataField="CategoryName" HeaderText="Category Name" />

<asp:TemplateField HeaderText="Products">

<ItemTemplate>

<asp:DropDownList ID="DropDownList1" runat="server">

</asp:DropDownList>

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

Populating the DropDownList:

Now, it is time to populate the DropDownList control. I used the GridView_RowDataBound event to populate the DropDownList. Take a look at the method below:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

DataTable myTable = new DataTable();

DataColumn productIDColumn = new DataColumn("ProductID");

DataColumn productNameColumn = new DataColumn("ProductName");

myTable.Columns.Add(productIDColumn);

myTable.Columns.Add(productNameColumn);

DataSet ds = new DataSet();

ds = GetDataSet();

int categoryID = 0;

string expression = String.Empty;

if (e.Row.RowType == DataControlRowType.DataRow)

{

categoryID = Int32.Parse(e.Row.Cells[0].Text);

expression = "CategoryID = " + categoryID;

DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList1");

DataRow[] rows = ds.Tables[0].Select(expression);

 

foreach (DataRow row in rows)

{

DataRow newRow = myTable.NewRow();

newRow["ProductID"] = row["ProductID"];

newRow["ProductName"] = row["ProductName"];

myTable.Rows.Add(newRow);

}

ddl.DataSource = myTable;

ddl.DataTextField = "ProductName";

ddl.DataValueField = "ProductID";

ddl.DataBind();

}

}

Explanation of the code:

The first thing I did is to create a DataTable which will contain the ProductID and the ProductName.

DataTable myTable = new DataTable();

DataColumn productIDColumn = new DataColumn("ProductID");

DataColumn productNameColumn = new DataColumn("ProductName");

myTable.Columns.Add(productIDColumn);

myTable.Columns.Add(productNameColumn);

After creating the DataTable I get the DataSet using the GetDataSet method. 

DataSet ds = new DataSet();

ds = GetDataSet();

The GridView already contains the CategoryID and CategoryName data since I populated it inside the Page_Load event. On that basis I retrieve the CategoryID from the GridView and generate an expression.

categoryID = Int32.Parse(e.Row.Cells[0].Text);

expression = "CategoryID = " + categoryID;

The expression is used on Table[0] and acts as a criteria on the Products table.

DataRow[] rows = ds.Tables[0].Select(expression);

Now, all the products associated with the particular category are inside the DataRow array. I parse through the array and populate the DataTable I created earlier.

foreach (DataRow row in rows)

{

DataRow newRow = myTable.NewRow();

newRow["ProductID"] = row["ProductID"];

newRow["ProductName"] = row["ProductName"];

myTable.Rows.Add(newRow);

}

After the DataTable is populated I simply assign it to the DropDownList.

ddl.DataSource = myTable;

ddl.DataTextField = "ProductName";

ddl.DataValueField = "ProductID";

ddl.DataBind();

Conclusion:

After the GridViewRow is databound you will notice that each of the template column contains a DropDownList which displays information related to a particular category. In this article you learnt that how you can create as well as display one to many relationships inside the GridView control using DropDownLists.

I hope you liked the article, happy coding!


 


 

 

By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: Hi to all gridviewguys
Name: sudhakar
Date: 1/24/2007 1:07:51 AM
Comment:
This article is very nice, but i want insert the check box at heaer of the grid view table when i select that check box all the reamning check boxes in that check box column will be selected.

This is my criteria please forword the links appropriate this one

Thank u.
Subject: RE:
Name: AzamSharp
Date: 1/24/2007 9:00:39 AM
Comment:
Hi Sudhakar,

Yes, you can easily do this. Check out my article using the following link:

http://gridviewguy.com/ArticleDetails.aspx?articleID=228

Subject: Grid View in asp.net 2.0
Name: neeraj kumar
Date: 2/6/2007 11:47:01 PM
Comment:
It's very nice example to understand the GridView server control.
Subject: new row
Name: asp.net novice
Date: 2/8/2007 3:54:48 PM
Comment:
Is it possible to move the drop down menu for each category to a new row beneath the category?
Subject: Request for code
Name: Ramya
Date: 2/8/2007 11:45:21 PM
Comment:
Hi


I am having a grid for tht i have added a column in tht column i have taken another grid . in tht grid i have taken 2 link buttons.

My requirement is when i click on any of the linkbutton i have to get the selected row col1 value so tht i can use tht value. Does anyone help in this task.I have a solution mail to me
Subject: gridview
Name: Sameer Ali Khan
Date: 2/14/2007 8:34:49 PM
Comment:
Dear Azam!
Its very nice and helpful code.Many of my issues are resolved.
Keep it up.
Subject: Superb
Name: Himanshu Sharma
Date: 2/16/2007 2:52:31 AM
Comment:
Hi,
Really really....... this is very helpful.
Thanks a lot
Subject: Can you this also in vb.net?
Name: gerbrand
Date: 3/22/2007 6:24:18 AM
Comment:
Hi, i just wanted to know if this is also possible in vb.net... I tried it, but nothing worked...

if someone can help me with this.
Thanks
Subject: update gridview with ddl
Name: nico
Date: 4/10/2007 11:44:14 AM
Comment:
can you use this list to update the row?
do you have an example for that
thank you
Subject: RE: Update GridView With DDL
Name: AzamSharp
Date: 4/12/2007 1:10:03 PM
Comment:
I would be glad to help you. Can you provide more details?
Subject: Selected value of dropdown list
Name: Benjamin Legaspi
Date: 4/19/2007 11:07:39 AM
Comment:
Say you have a gridview of employees and the last column is a dropdown list consisting of job titles (e.g., programmer, manager, secretary). You populate the gridview using data from a table and want the appropriate title to display on Page_Load. Can you do this? I'm using VB and can only get the dropdown to display the first item for all the rows. Thanks for any advice.
Subject: study
Name: gajendrasingh
Date: 5/2/2007 9:19:37 PM
Comment:
dear sir,
please give me some examples in c#.NET GRIDVIEW(EVENT EDIT,DELETE,UPDATE).

THANKING YOU
Subject: I worked it on a Grid View Edit Template
Name: Nitin
Date: 5/3/2007 4:05:37 PM
Comment:
Well you really gave me an idea. Thanks
Subject: Nice JOB
Name: Prasad
Date: 5/4/2007 8:59:02 AM
Comment:
Hi buddy
Gud JOB.
Keep it UP.
Subject: getting values from the dropdownlist
Name: guna
Date: 5/6/2007 8:07:16 AM
Comment:
hi guys
The article is good, but i want to get the values of dropdownlist which i have have placed in griedview

after selecting the values from the dropdownlist then i have to fill another dropdownlist based on the first dropdownlist vales

both the dropdownlists are placed on the grid viwe control.

please help me.
Subject: gridview with two table
Name: prashant
Date: 5/12/2007 2:10:46 AM
Comment:
This is a very good example of gridview that binding two table data in one single gridview.

This is a very good example of programming.

many many
Thankssssssssss
Subject: Help with DropDowns
Name: RobertM
Date: 5/17/2007 8:48:03 AM
Comment:
Thanks for the above code but I think I need a little more direction.

Alright I have almost got this application finished but I am totally stuck and have been stuck for the last several days so I think that I now need some more help. To review this is what I have. I have two tables one named oncall and one named mainphonelist. The oncall table displays the information in a datagrid view and consists of the following fields:

Application - Primary Key
Name
Cell
Pager
Office
Comment

The MainPhonelist is the pool of all possible people who can be on call and it contains the following fields:

Name
Cell
Pager
Office

What I have done so far is create the gridview that shows all the data in the oncall table. When edit is clicked a dropdownlist is presented to the user containing all possible people from the mainphonelist.

Now here is the issue. I want the cell, pager, and office fields to update when the user selects a name from the drop down list with the corresponding information for that name. So for example, If I select John Doe from the list I would like to populate the cell, pager, and office fields with John Doe's information from the mainphonelist.

I know the program code needs to go into the DropDownList1_SelectedIndexChanged sub but I don't know what code I would use. I have tried the gridview1.selectedrows.cells(2).text object but I can't update it because it is readonly.

All Help is appreciated.
Subject: Help Required
Name: Arsalan
Date: 5/31/2007 10:12:05 PM
Comment:
Hi,

I have a ddl in a grid view edit item template . I bind the ddl on gridview row data bound event.Now i am not able to get the newly selected value of ddl in my update function.

Any ideas how to achieve this?

Thanks!
Subject: Updating
Name: Nuke
Date: 6/4/2007 9:09:15 AM
Comment:
Can you provide code on how to update the database once one of the dropdown has been changed?
Subject: dropdown list view in editmode
Name: Rehan Wahab
Date: 6/13/2007 5:00:33 AM
Comment:
Very nice example.
kindly send me any one example above subject.


Thanx
Subject: ListBox in Datagrid
Name: priya.K
Date: 6/15/2007 4:28:42 AM
Comment:
Instead of Grid view control i used Datagrid.while populating the data into the listbox i got the error as "Object reference not set to an instance of the object"
kindly tell me the sollution

"IT IS VERY URGENT"

Subject: Why is this so hard?
Name: Walter
Date: 6/18/2007 9:44:29 AM
Comment:
WHY is it so hard to do this? Even with this superb example, the built in controls still wont do what I want them to do.

All I want is to display in my grid with a dropdown control. That control should BIND to a field in a table and offer VALUES FROM WHICH TO SELECT from another table. Why doesnt the people working on ASP.Net talk to the Access people. Access got it right, why doesnt ASP.NET???
Subject: Hi..
Name: Durga Prasad
Date: 6/19/2007 4:08:09 AM
Comment:
I think more explanation is required to understand the code.
Subject: Binding the Selected value
Name: Neil
Date: 6/19/2007 7:45:55 AM
Comment:
I have the dropdown lists being populated correctly but what I need to know is how do I bind the SelectedValue?

When I add SelectedValue='<%# Bind("TestRequestId") %>' to the dropdownlist markup I get an "Object reference not set to an instance of an object" runtime error

Help would be gratefully appreciated
Subject: gridview
Name: sura
Date: 7/5/2007 6:53:39 AM
Comment:
the article is very useful, but I wonder if you could give more detailed information about rowdatabound event method part.
thank you..
Subject: RE: GridView
Name: AzamSharp
Date: 7/5/2007 5:29:04 PM
Comment:
Hi,

Let me know what details you need for the GridView_RowDataBound event.
Subject: comments
Name: sandeeppathania
Date: 7/9/2007 4:37:09 AM
Comment:
this article is really brilliant
Subject: How to insert
Name: siva
Date: 8/26/2007 11:53:04 PM
Comment: