DropDownList inside a GridView (or DataGrid)
I'm still coming up to full speed on ASP.NET, as evidenced by a conversation I had yesterday about Grids and DropDownLists and their events. In the interest of reinforcing the concepts, I've implemented a sample page and am summarizing it here to further commit it into my brain.
The page requirements:
1) Table/Grid displays a list of states (U.S. states) with a column for the state name and a column that contains a dropdown list of the state's cities.
2) Upon selecting a city, the page will display the city name (and perhaps futher lookup some information specific to the city).
The basic ASP.NET flow here is (using 2.0 here, but works similarly in 1.1 using DataGrid):
1) Create a GridView with a bound column for state and a template column for the DropDownList
2) Create a label to display the city name upon selecting it in the DropDownList.
3) Bind the GridView to an array of state objects (could be bound to many other things as well, but keeping it simple for this example). State contains properties for Name and for Cities.
4) Hookup RowCreated event on the GridView so that we can populate the cities into the particular row's DropDownList.
5) Add postback event for getting the selected city and populating the label with it.
Here's what the aspx code looks like:
And here's the code behind:
This code should be more defensive with null checking, type checking and exception handling in place. But, you get the idea of the general work flow (and now, so do I).
A couple of points that I'd like to highlight:
- AutoPostBack is required on the DropDownList in order to submit the page immediatlely opon selecting an item. For some reason I thought if the event was there, that was all that was needed (time to come out of my WinForms haze).
- Use the FindControl() method to grab a reference to the DropDown.
- In this case RowCreated or RowDataBound would work for binding the DropDownList. If you needed the State name to lookup cities, you would need to use RowDataBound. However in this case, since the object we're bound to already has the cities, RowCreated works fine too.
The page requirements:
1) Table/Grid displays a list of states (U.S. states) with a column for the state name and a column that contains a dropdown list of the state's cities.
2) Upon selecting a city, the page will display the city name (and perhaps futher lookup some information specific to the city).
The basic ASP.NET flow here is (using 2.0 here, but works similarly in 1.1 using DataGrid):
1) Create a GridView with a bound column for state and a template column for the DropDownList
2) Create a label to display the city name upon selecting it in the DropDownList.
3) Bind the GridView to an array of state objects (could be bound to many other things as well, but keeping it simple for this example). State contains properties for Name and for Cities.
4) Hookup RowCreated event on the GridView so that we can populate the cities into the particular row's DropDownList.
5) Add postback event for getting the selected city and populating the label with it.
Here's what the aspx code looks like:
<asp:GridView ID="gvStates" AutoGenerateColumns="false"
runat="server" OnRowCreated="gvStates_RowCreated">
<Columns>
<asp:BoundField HeaderText="State" DataField="Name" />
<asp:TemplateField HeaderText="Cities">
<ItemTemplate>
<asp:DropDownList ID="ddlCities"
AutoPostBack="true" runat="server"
OnSelectedIndexChanged="ddlCities_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="lblCity" runat="server" Text="Label">
</asp:Label>
And here's the code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Create states array and bind it to Grid
ArrayList states = new ArrayList();
string[] cities =
new string[] { "Portland", "Salem", "Eugene" };
State state = new State("OR", cities);
states.Add(state);
cities =
new string[] { "Seattle", "Tacoma", "Olympia" };
state = new State("WA", cities);
states.Add(state);
this.gvStates.DataSource = states;
this.gvStates.DataBind();
}
}
protected void gvStates_RowCreated(object sender,
GridViewRowEventArgs e)
{
if (!IsPostBack)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Bind drop down to cities
DropDownList ddl =
(DropDownList)e.Row.FindControl("ddlCities");
ddl.DataSource = ((State)e.Row.DataItem).Cities;
ddl.DataBind();
}
}
}
protected void ddlCities_SelectedIndexChanged(object sender,
EventArgs e)
{
this.lblCity.Text = ((DropDownList)sender).SelectedValue;
}
This code should be more defensive with null checking, type checking and exception handling in place. But, you get the idea of the general work flow (and now, so do I).
A couple of points that I'd like to highlight:
- AutoPostBack is required on the DropDownList in order to submit the page immediatlely opon selecting an item. For some reason I thought if the event was there, that was all that was needed (time to come out of my WinForms haze).
- Use the FindControl() method to grab a reference to the DropDown.
- In this case RowCreated or RowDataBound would work for binding the DropDownList. If you needed the State name to lookup cities, you would need to use RowDataBound. However in this case, since the object we're bound to already has the cities, RowCreated works fine too.
49 Comments:
Still not working yaar !!!
By Anonymous, at 1:12 PM
fyi:
the key to making this work is to have the if(!Page.IsPostBack) on page load.
If you don't have this - it wouldn't work.
Steve
By Anonymous, at 5:23 PM
thnx for the code..
if i wanna update a field(here dropdownlist selectedvalue* textbox's chanegd text) and send it to as a parameter to an
SP(when i click the update command buton inside the gridview)0 what code shud i write inside the row_updating () event ?
i am having a dropddownlistas a template field inside a gridview & textbox also as a temlate ina different column.
how can i update the value sin the DBase whel te user selects a item inside the combo & changed the text inside the tetbox?
plz giev me the code..
By Anonymous, at 8:13 AM
"please give me the code" hahaha.. man for some reason that just seems so rude.
By Anonymous, at 12:20 PM
Hi. I would like to know when the item index is changed, how would i get the gridview Row ID?
By Anonymous, at 6:00 AM
can u plz explain for dropdownlist inside a datagrid ?
By Anonymous, at 6:22 PM
An EXCELLENT Code!!!!!
I've walked through a lot of articles/tutorials/videos/examples and this was the BEST!
It is short, simple and gets to the point. BOOM! you nailed it!
By Unknown, at 11:47 AM
Well,
I looked through the codes, and WTF?
By Anonymous, at 1:52 PM
I am getting an error when i create an instance of "State" like in the code
string[] cities = new string[] { "Portland", "Salem", "Eugene" };
State states = new State("OR", cities);
states.Add();
By Anonymous, at 11:21 AM
Code is ok however not very much clear
By Anonymous, at 2:30 AM
hi i also problem at this point blow code
Array states = new Array();
string[] cities = new string[] { "Portland", "Salem", "Eugene" };
State state = new State("OR", cities);
states.Add(state);
By rakeshpatil, at 2:02 AM
the code for the State class is missing, i can't get to work this example o seaa
By Anonymous, at 1:53 PM
Who can explain for me "State" is?
Thankyou!
By Nguyễn Ngọc Việt, at 8:50 PM
Error 1 The type or namespace name 'State' could not be found (are you missing a using directive or an assembly reference?) C:\Documents and Settings\dneelands\My Documents\Team Projects\LunchGenie3\test.aspx.cs 25 13 C:\...\LunchGenie3\
Please define the State object?
By Anonymous, at 8:38 AM
You could also make use of a hidden control in the page (and in this case an update panel) as part of the data source, so when the page 'reloads' it has the necessary parameter to populate the second dropdown with less actual coding required. (ajax is optional)
In the aspx file...
ok... take 2 no asp scripting can be posted in comments... You are going to get the watered down version. (use your imagination to figure out where the tags begin and end :-)
asp:SqlDataSource ID="UniqueMenusDataSource" runat="server"
ProviderName="ConnectionStrings:LibertyDatabaseReadWrite.ProviderName
SelectCommand="SELECT distinct [menu] FROM [Menus] WHERE [screen] = ?"
asp:SessionParameter Name="?" SessionField="CurrentClientID" Type="Int32"
asp:ControlParameter ControlID="txtBoxMenuGroup" Name="?" PropertyName="Text"
SelectParameters
asp:SqlDataSource
asp:DropDownList ID="MenuGroupScreensDropdown" runat="server" DataSourceID="UniqueScreensDataSource" AutoPostBack="true" OnSelectedIndexChanged="MenuGroupScreensDropdown_SelectedIndexChanged"
asp:DropDownList
asp:TextBox ID="txtBoxMenuGroup" runat="server"
asp:DropDownList ID="MenusDropDown" runat="server" DataMember="DefaultView" DataSourceID="UniqueMenusDataSource"
DataTextField="menu" DataValueField="menu" Width="88px"
In the code behind:
protected void MenuGroupScreensDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
txtBoxMenuGroup.Text = MenuGroupScreensDropdown.SelectedValue;
MenusDropDown.DataBind();
}
I used this to success in the CNC work order system I support where many options are dependent on previous choices made by the user.
Greg.
CNC Workorder System
By Greg McKone, at 9:19 PM
Here is the State Class
public class State
{
private string _Name;
private string[] _Cities;
public State(string name, string[] cities)
{
_Name = name;
_Cities = cities;
}
public string Name
{
get{ return _Name;}
}
public string[] Cities
{
get{ return _Cities;}
}
}
By betameister, at 7:26 PM
You know ,I have some priston tale Gold,and my friend also has some
priston tale Money,do you kouw they have the same meaning,I just want to
buy priston tale Gold,because there are many cheap priston tale Gold
You know ,I have some wow gold,and my friend also has some
World of Warcraft Gold,do you kouw they have the same meaning,Both of them can be called
warcraft gold,I just want to
buy wow gold,because there are many
cheap wow gold
By Anonymous, at 6:12 PM
i can get maple mesos cheaply,
Yesterday i bought mesos for my brother.
i hope him like it. i will give maple story mesos to him
as birthday present. i like the cheap mesos very much.
I usually buy the maplestory mesos and keep it in my store.
I can get LOTRO Gold cheaply.
Yesterday i bought Lord Of The Rings Gold for my brother.
i hope him like it. i like the cheap Lord Of The Rings Gold very much.
I usuallybuy LOTRO Gold and keep it in my store.
By Anonymous, at 5:38 PM
As a new player , you may need some game guides or information to enhance yourself.
aoc gold is one of the hardest theme for every class at the beginning . You must have a good way to manage your conan gold.If yor are a lucky guy ,you can earn so many age of conan gold by yourself . But if you are a not , I just find a nice way to get cheap aoc gold. If you need , you can buy aoc money at our website . Go to the related page and check the detailed information . Once you have any question , you can connect our customer service at any time .
By Anonymous, at 7:46 PM
Do you know 2moons dil? I like it. My brother often go to the internet bar to buy 2moons gold and play it. After school, He likes playing games using these 2moon dil with his friend. One day, he give me many buy 2moons dil and play the game with me. I came to the bar following him and found cheap 2moons gold was so cheap.
By Anonymous, at 5:49 PM
I always believe the angel is being and 12sky2 Gold . In fact, we all like listening to the songs of milk tea twelve sky2 Gold .
Generally speaking, I think is her voice very comfortable and mood of the story twelvesky2 Gold , We feel life bit by bit, looking forward the love belonging of the life feelings buy 12sky2 Gold , you will love milk tea like me, let us love her together and play cheap twelve sky2 Gold .
By Anonymous, at 5:57 PM
Due to make cheap rf gold the intense gravity on their home planet, the Bellato are the smallest people. rf gold which in RF Online Game is very popular for many players. Play this online game the premise that we have more enough rf online gold first. They are able to combine creative tools and weapons with some rf money and the Light form of universal magic. Under such sustained attacks they fell from power, yet they have bided their rf cp and time.
We only plan to pay cheap rs gold when we feel you will appreciate the updates. And we certainly feel that these changes and some runescape money are worth telling you about. runescape gold of RS Online Game, we have made several changes to Fun Orb. If you wish to buy runescape to explore other spell books, you should subscribe as a Fun Orb member. Shattered Plans - a galaxy-spanning strategy epic that use rs gold to allow up to six players to battle for supremacy.
By Anonymous, at 7:23 PM
your post is helpful and informative
By website design New York City, at 6:50 AM
Czyść brudną tapicerke z karcher odkurzaczem, tanio i wygodnie. Czyszczenie dywanów odbywa się szybko i dokładnie.
Promocje związane z czyszczenie dywanów tapicerki samochodowej jest na prawdę tanie.
Czyszczenie odbywa się na mokro. Dywan, tapicerka samochodowa i meblowa. Czyść spontanicznie i nie nerwowo ale pewnie i tanio.
By Anonymous, at 8:10 AM
i have used the same as like u but i have written it on Gridview_RoDataBound ie: the Selectedindex_ChangeEvent works on Localhost but the same was not working on Live , when i upload it on server ??
Why ??
Any solution
By Venkat, at 9:13 PM
good article...helped a lot...thanks ....
By Anonymous, at 12:05 AM
thns 4 nice article
By Anonymous, at 12:16 AM
I think it's better to use the effect of quasistochastic matrix with relation to stochastic tympanism. Your method is good too, but it is very wening in a case of coherent materialism. Also draw your attention to the mexican gambit tactic:
Array states = new Array();
string[] cities = new string[] { "Portland", "Salem", "Eugene" };
State state = new State("OR", cities);
states.Add(state);
Becouse it is not works!
By Unknown, at 6:41 AM
http://www.crisc.ru/
By Anonymous, at 1:19 AM
Nike Outlets Online
Nike Air Max 2011
Nike Air Max 24 7
Nike Air Max Bw
Nike Air Max Tn
Nike Air Presto
Nike Air Max Ltd
Nike Air Zoom Kobe
Nike Air Max Boots
Vibram Five Fingers Shoes
Nike Air Max Fitsole
Nike Air Max Goadome
Nike Air Max Skyline
Nike Air Max Turbulence
Nike Air Wildwood Supreme
Nike Outlet Stores Online
Nike Outlet Mall
Nike Air Griffey Max 1
Nike Air Max 1
Nike Air Max 180
Nike Air Max 87
Nike Air Max 90
Nike Air Max 91
Nike Air Max 95
Nike Air Max 2009
Nike Air Max 2010
By abercrombiefitch, at 12:24 AM
I value what you guys are usually up too. This kind of clever work and reporting! Keep up the great posts guys I've added you to my blogroll, Cheers. Here useful link:Runescape gold Tera Online Tera gold cheap wow gold
By Runescape gold, at 11:36 PM
Tera gold
Tera Item
Tera account
Runescape gold
buy Runescape gold
cheap wow gold
cheapest wow gold
lotro gold
Tera online
Tera gold
Tera items
Tera gold cheap
cheap Tera gold
By cheaptera, at 1:04 AM
Your Escort Agency offers exclusive and most beautiful London escort girls of various nationalities.
By London Escort Agency, at 1:44 PM
Bestescort4U agency provids best London escorts companionship in the UK.
By London escorts, at 12:30 PM
thanks for the post .net is a great development package.
By fix credit score, at 8:56 PM
Thanks for the informative writing. Would mind updating some good tips about it. I still wait your next place.Marvelous length to be born. Amber’s wedding dresses 2012 collection configures the theory of woman’s golden proportion by revealing an unexpected power of wavy skirts. Our magical tea length wedding dresses with illusive overlay would bring you back to the spring-like girlhood. Willing to go with us??
By ambersbridal, at 7:03 PM
I also do agree with the stuff you shared, Thanks that's a wonderful post.
Facebook and Twitter Marketing
By Knox Karter, at 2:22 AM
Thank you for another great article. Where else could anyone get that kind of information in such a perfect way of writing? I have a presentation next week, and I am on the look for such information.
Media Logo
By Knox Karter, at 6:06 AM
Thanks a lot, I had been trying to bind it in RowBound event but the FindControl didn't work, this really helped me!!
By Casiel, at 10:55 AM
if you want use this with PostBack just use this
if (e.Row.DataItem == null)
{
return;
}
after you find a dropdownlist and before you set DataSource
By Anonymous, at 6:38 AM
From the advertisements, we are able to research theirs propagate priority. The complete atmosphere is as following: the framing is situated within of tiffany stores the romantic island, using the intent of constructing an fast and at ease atmosphere. The type Anne Vyalisyna wears a apparel with flouncing and coach on sale different delicate fits walking for the trip. The visual appeal of gentle yellow, pale pink and gentle blue will make the complete assortment diffuse the inhale of youthful lady and pleasant mood; she appears like really graceful, easy-going and converse store livelier. LV bag 2011 is mainly developed using the gentle yellow, pale pink and gentle blue colors, the ads are filmed near to this theme color.
By converse store, at 8:27 PM
How do you think about Diablo 3? Do you play it or do you want some D3 gold? I kown a good website to by Diablo 3 gold. If you want, just click it.
By summerlijia, at 7:00 PM
I want to ask that this code can be work in blogger if I want drop down side grid view in blogger or WordPress? because I am interesting in this so, if possible, kindly guide me how I manage this code in blogger or WordPress.
By Flash Game Developer, at 11:57 PM
Hello Dear, Really your blog is very interesting.... it contains great and unique information. I enjoyed to visiting your blog. It's just amazing.... Thanks very much.
By CitraIndah - Kota Nuansa Alam Timur Cibubur, at 1:28 AM
DataGridView dropdown selection in C#
By Anonymous, at 1:43 AM
Really important written content. the information that you shown is hard to faith and many superbly i liked the way you afford things here
By Accredited GED Online, at 11:39 PM
good commands
By Anonymous, at 8:57 PM
khk
By Anonymous, at 8:57 PM
I always wonder what it would be like if these kind of posts were never online. How would people find the information they need. You are doing a great job of blogging, giving the readers a chance to be informed on various issues. Thank you very much and it would be a great thing to keep finding more on your pages.
College Essay Writers Online
By Expertise for Hire, at 11:58 PM
Post a Comment
<< Home