How to set DDL's selected value by datasource other than DDL's datasource

I have three TemplateFields in a Gridview. In each, the ItemTemplate has a label whose text value is bound to the GridView's DataSource. But in the EditItemTemplate the DropDownList is populated with a separate DataSource. This is a fairly common setup, so that wasn't too much to deal with.

What I need to do is, when the GridView goes in to Edit mode and the DropDownList is populated and displayed I want the value that was in the bound label to be the default selected value in the DropDownList. As it currently is, the DropDownList renders with "Select..." as the default value regardless of the actual value for that field in the table. And as you probably know, clicking update as it is now would actually update that field with an empty string.

Here's the relevant code for one of the DropDownLists and its DataSource:


<asp:gridview id="gvDataPoint" runat="server" autogeneratecolumns="False" datasourceid="dsDataPoint"
	allowpaging="True" pagesize="20" allowsorting="True" datakeynames="DataPointID"
	borderwidth="0px" borderstyle="None" rowstyle-backcolor="whitesmoke" rowstyle-height="27px"
	alternatingrowstyle-backcolor="#FFFFBB" pagerstyle-horizontalalign="Center" pagerstyle-backcolor="#CCCC99"
	headerstyle-backcolor="#CCCC99" rowstyle-font-size="10px">
		<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" HeaderStyle-Width="125px" />
		<asp:TemplateField HeaderText="L0PDUnit" HeaderStyle-Width="100px">
				<asp:Label ID="lblL0PDUnitID" runat="server" Text='<%# Bind("L0PDUnit") %>' />
				<asp:DropDownList ID="ddlEditL0PDUnitID" runat="server" DataSourceID="dsL0PDUnitForDdl"
					DataTextField="ShortName" DataValueField="L0PDUnitID" SelectedValue='<%# Bind("L0PDUnitID") %>'
					<asp:ListItem Text="Select..." Value="" />

<asp:ObjectDataSource ID="dsL0PDUnitForDdl" runat="server" SelectMethod="GetL0PDUnitforDDL"
	TypeName="AgCodeNET2.BusinessObject.DataPointSystem" />
<asp:ObjectDataSource ID="dsDataPoint" runat="server" SelectMethod="GetListDataPoint"
	DeleteMethod="DeleteDataPoint" InsertMethod="UpdateDataPoint" UpdateMethod="UpdateDataPoint"
		<asp:Parameter Name="DataPointID" Type="int32" />
		<asp:Parameter Name="DataPointID" Type="Int32" />
		<asp:Parameter Name="L0PDUnitID" Type="Int32" />
		<asp:Parameter Name="DataPointID" Type="Int32" />
		<asp:Parameter Name="L0PDUnitID" Type="Int32" />

 As you can see by the ObjectDataSources, we use a business layer for the data. I have to use a stored proc for any select, update, edit, delete, etc. Any other questions to help clarify, please let me know.


"f u cn rd ths, u cn gt a gd jb n cmptr prgmmng." - Anon
8/9/2007 1:58:15 PM 72751 articles. 3 followers. Follow

10 Replies

Similar Articles

[PageSpeed] 28

Can't you then just change the binding of the SelectedValue property to the "L0PDUnit" field instead? Outsid of that, I'd mention that it's a good idea to place the ObjectDataSource for your DropDownList within the same template.

Thanks, Ed

Microsoft MVP - ASP/ASP.NET

8/9/2007 2:39:01 PM

Thanks, ecbruck, but unfortunately that won't work. "L0PDUnit" isn't in the SELECT statement of the DropDownList's DataSource. It's a column alias in the SELECT for the GridView's DataSource.

I'm not sure if I need to do this somehow in my stored proc or in the code-behind.

"f u cn rd ths, u cn gt a gd jb n cmptr prgmmng." - Anon
8/9/2007 3:45:06 PM

That's the whole point. The data-binding for the SelectedValue property of your DropDwonList should come from a field within your GridView's DataSource. It doens't have to have the same name a field being bound to your DropDownList as long as the underlying value from the GridView.DataSource lies somewhere within the DropDownList value items.

Thanks, Ed

Microsoft MVP - ASP/ASP.NET

8/9/2007 3:54:11 PM

Okay - I do understand what you mean by that last post, but in this case what I want to do is allow the user to change the L0PDUnit to any L0PDUnit from the L0PDUnit table.

Using just the column in my example above, here's the GV's stored proc:


dp.DataPointID, --PKey column
L0.ShortName as L0PDUnit
FROM DataPoint dp

 As you can see by the stored proc, there's a L0PDUnitID column in the DataPoint table that points to the corresponding shortname in the L0PDUnit table. Since I want to allow the user to change the value in the ShortName column in the DataPoint table to any listed in the L0PDUnit table, I used the DDL with it's own DataSource. Here's the SELECT for the DDL:

L0PDUnitID, --PKey column
ORDER BY ShortName

 Maybe that's more information than you need, or maybe it's not even relevant to what you're trying to say (in which case I'm obviously not understanding - sorry), but I hope it helps.


"f u cn rd ths, u cn gt a gd jb n cmptr prgmmng." - Anon
8/9/2007 4:11:25 PM

Ok, then your code should work. How about removing the AppendDataBoundItems property along with the hard-coded ListItem. Does it work then? If so, and you still want to add your intial item into the list, then you can inset this ListItem during the DropDownList.DataBound event.

Thanks, Ed

Microsoft MVP - ASP/ASP.NET

8/9/2007 4:25:34 PM

No dice :(

I removed the AppendDataBoundItems property and the hardcoded "Select...". It took me a while to figure out that I also had to remove the  bound "SelectedValue" property from the DDL code as well. So here's what my DDL looks like now:


<asp:TemplateField HeaderText="L0PDUnit">
		<asp:Label ID="lblL0PDUnitID" runat="server" Text='<%# Bind("L0PDUnit") %>' />
		<asp:DropDownList ID="ddlEditL0PDUnit" runat="server" DataSourceID="dsL0PDUnitForDdl"
			DataTextField="ShortName" DataValueField="L0PDUnitID">

 Now, when the GV goes to edit mode the default selected value is the first item in the list from the stored proc, of course. But again, presumably since the DDL is using a different DataSource, whatever is selected in the DDL doesn't get into the Update. Plus I still need the DDL to default to whatever value that record has there.

This question is getting more into the realm of SQL-specific stuff, but is there any way to use my select stored proc for the GV to also "hold" the info for the DDL? I'm guessing not and that's not the direction to go to solve this...


"f u cn rd ths, u cn gt a gd jb n cmptr prgmmng." - Anon
8/9/2007 5:37:27 PM

I think I see what's happening now. In the DataSource feeding your GridView, your returning the "ShortName" field from the "LOPDUnit" which is associated with the "LOPDUnitID" field in the "DataPoint" table. You can't bind to the SelectedValue property of the DropDownList because the value field is bound to the "LOPDUnitID" field of the "LOPDUnit" table. These two obviously don't mesh.

In the query for your GridView, you should simply dump the join and return the "LOPDUnitID" field from the "DataPoint" table. If you do this, no your fields will match up. Then you can simply bind "LOPDUnitID" to the SelectedValue of your DropDownList.

Thanks, Ed

Microsoft MVP - ASP/ASP.NET

8/9/2007 6:03:00 PM

I think I understand what you mean. However, the ASPX and SQL code I provided above is only pertaining to the fields relevant to the question (at the time). Your suggestion to drop the join kind of sent up a red flag, only because of what else is going on in the GV and stored proc. Here's the full stored proc that populates the GV (the actual GV displays all of these columns and the Update uses all of them as well):


CREATE PROCEDURE dbo.sp_dpa_GetDataPoint
dpt.ShortDescription as DataPointType,
l0pdu.ShortName as L0PDUnit,
l1pdu.ShortName as L1PDUnit,
FROM locn_DataPoint dp
LEFT JOIN locn_DataPointType dpt ON dp.DataPointTypeID = dpt.DataPointTypeID
LEFT JOIN locn_L0PDUnit l0pdu ON dp.L0PDUnitID = l0pdu.L0PDUnitID
LEFT JOIN locn_L1PDUnit l1pdu ON dp.L1PDUnitID = l1pdu.L1PDUnitID
WHERE dp.Deleted IS NULL
ORDER BY l1pdu.ShortName, dp.IdentityNumber

 So you see, I dummied down the code a good bit earlier. In light of that, I'll emphasize that the GV needs to display the ShortName (not the L0PDUnitID - and not to be confused with the dp.ShortName field!) that comes from the joined L0PDUnit table. And also, of course, a list of all ShortNames in a DDL from the L0PDUnit table when the GV is in edit mode. 

You suggested I "dump the join and return the L0PDUnitID from the DataPoint table". I'm not sure I can do that and still have a bound label in the GV displaying the ShortName gotten from the L0PDUnit table.  Either I misunderstand what you're suggesting in your last post, or this added info changes what you would suggest...

I fear I may be confusing things, so please let me know if I need to clarify!

Thanks a lot for your help!

"f u cn rd ths, u cn gt a gd jb n cmptr prgmmng." - Anon
8/9/2007 6:52:48 PM

Then you still need to return the "LOPDUnitID" field from the "DataPoint" table or you can't bind to the SelectedValue of your DropDownList.

Thanks, Ed

Microsoft MVP - ASP/ASP.NET

8/9/2007 6:58:35 PM

Well, whaddya know - it was a simple matter of adding dp.L0PDUnitID & dp.L1PDUnitID to the SELECT stored proc! (Which is what I think you just said in your last post!) Surprise

Thanks a million for your help, ecbruck!

"f u cn rd ths, u cn gt a gd jb n cmptr prgmmng." - Anon
8/9/2007 8:08:04 PM

Similar Artilces:

Help! I cannot access the DataGrid's ItemTemplate's LinkButton's Text Atrribute 's Value!!!!!!!!!!!
I write a datagrid's ItemDataBound method as follows:   private void dgTable_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)  {   if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)   {    if(!isRole("Manager"))    {     LinkButton tmp = (LinkButton)e.Item.FindControl("lbPassed");     if(tmp.Text == "Passed")     {      ((LinkBu...

Can a User Control's Page_Load retrieve a value set in the parent's Page_Load?
I want to use a control to perform a specific task, but I want it to vary based on the page it is on. I was hoping to set a value in the Page_Load event of the Parent, and have that value retrieved by the Page_Load event of the user control. I am not sure what order these events fire in, Can I be certain that the parent event will fire first?...

Setting a panel control's visibility and it's affect in nested controls.
I am trying to debug a page using the panel control.  The code in the final submission of the form has logic to get data from a dropdown based on the control's visibility.  If the control's visibility is set to true, the the data is retrieved and sent to the database.The problem appears to be the dropdown control's visibility is set to false when it should not.  The dropdown is nested in a panel control.  While doing a trace, it appears when a panel control's visibility is set to false, the visibility for all controls nested under this panel are set to false as well.You'r...

Label control's text doesn't appear to be set (in the page which has a user control )when trying to update the text property in the FormView's ItemUpdated event
Hi There,I have a user control which hosts a formview control, gridview control and a label control. The grid view is usedto show rows in the DB and when clicked to edit each row, a form view opens up in edit mode with that particular row info. So I have nothing in the item template.My first question it mandatory to have smth in the itemtemplate of the form view.I have controls in edititemtemplate and insertitemtemplate.When a particular row is edited, I would like to show a status msg showing that the row has been updated.For this, I use the ItemUpdated event of the formview and try ...

The value's length for key 'data source' exceeds it's limit of '128'.
Hii, When I tried to bind dropdownlist to database by declaring connection string in the code behind file I am getting this error: The value's length for key 'data source' exceeds it's limit of '128'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentException: The value's length for key 'data source' exceeds it's limit of '128'.Source Error: An...

Control's (object's) default value??
How or where can I see an control's default value? Say, for example the Visible property for webcontrols? Would be preferable if I could quickly see it in Visual Web Developer but MSDN online documentation would also be nice. Also how can I do this in general for all .Net objects?...

OLE Control
I'm attempting to load a .bmp image into an OLE object using PowerBuilder 11.1. The OLE ActiveX is AddFlow5 and I am using it to graphically represent links between entities - people, organisations, addresses, vehicles, telephones, etc. Documentation for AddFlow5 gives an example in VB script to load the relevant 'picture' into a node, ie, SET node.picture = LOADPICTURE("C:\images\person.bmp"). I cannot find a suitable equivalent in PB 11 to either 'SET' or to 'LOADPICTURE' The developer of AddFlow suggested I try: OLEObject uo uo = C...

Replace 1's and 0's in a gridview column with Yes's and No's
Is it possible to change the display of a column in a gridview to show a Yes for all 1's and a No for 0's that display in a particular column of a gridview bound to a database?  If so, can someone share the way with me?  I am using ASP.NET 2.0 with VB Code Behind.  Thanks One way you can do is thrrough  CASE in your select statement: Select YesNoColumn= CASE yourColumn WHEN 1 THEN 'Yes' WHEN 0 THEN 'No' ELSE '' END FROM YourtableLimno <Columns>     <asp:TemplateField HeaderText="yourHeader" SortExpression="yourDataField"> ...

ddl using LINQ: Need to set WHERE clause of LINQ data source to another table's PK. (use LINQ to join FK to seperate table's PK as part of WHERE)
This is a bit odd, but I have a drop down list that I want to use to display a list of values. These values are a list of products.  I want to filter this list of products by the product category.  HOWEVER, productCategory is NOT part of the products table.  There is a seperate many to many table that handles that. (Some products could be in multiple categories like how a video game at a store could be considered to be part of "Video Games", "Educational Games", "Games for the Xbox360" or whatever might make ense).  So what I have is: A li...

It's Linux !? No, it's BSD ! No, no, it's...
kFreeBSD a Debian distro using the FreeBSD kernel ! ObiWan wrote: > kFreeBSD > > > > a Debian distro using the FreeBSD kernel ! Why use a BSD kernel? I hope the reason is more than, just because they can. It's easy to understand why the would want to use Debian packages. :) -- Jimmy Johnson Registered Linux User #380263 >> kFreeBSD >> >> >> ...

how to control a RadioButtonList's Listitem's text show according database's field
Hi my page has a repeater control,in repeater has a RadioButtonList control now i want to let the RadioButtonList has four Listitem,every Listitem's text is a database's field so the listitem can show dynamic according every record how can i work out my problem thanks a lot  hello dearbound your RadioButtonList to database if i m not clear fell free 4 replySatyabrat SinghB.E.(C.Sc.)Web developer Livetek Solution Dont forget to click "Mark as Answer" on the post that helped you. yes.i bound the radiobuttonlist to a dataset but how to display the ...

Setting a panel's height to the height of it's parent control
How do I go about getting a panel to be the same height and width of the cell of the GridView or table that it is in?  I was under the impression that if you set the height of the panel to be 100%, then it would become 100% of the parent control.  In this case, I would assume that the parent control would be the cell that it is housed in. When I do this, it makes my entire GridView or table (I've tried both) grow in heighth by a dramatic amount.  I just want the panel to be the same height as the cell when they are each at their minimum height (based on the lines of text ...

DataSource Control's Selecting Event
Hi Asp.Net Team, Is it possible to change one of the values in the InputParameters dictionary of the ObjectDataSourceSelectingEventArgs class? The code is here: in the CreateChildControls i make this: anObjectDataSource.Selecting += new ObjectDataSourceSelectingEventHandler(this.ods_Selecting); -------------***------------------- this is my eventhandler: protected void ods_Selecting(object sender, ObjectDataSourceSelectingEventArgs e) { e.InputParameters[0] = 4; // something like this????? } Whatever I do here, I get this error: "Object must be o...

Hyperlink's, ImageURL's, and OnError's
I created an ASP:Hyperlink and set the ImageURL attribute so the link will be the image.If the image is missing, I would like it to display a 'missing image' pic that I have.  I know you can use the OnError attribute of the <img> tag to run some javascript to change it.Unfortunately I can't find a way to access the Hyperlink's Image that is inside it, so I can add an Attribute so the resulting <img> tag will have an OnError attribute inside of it.Any help?If my Hyperlink is called 'foo'....would I do...  ((Image) foo.Controls[0]).Attributes.Add(&...

Web resources about - How to set DDL's selected value by datasource other than DDL's datasource -

Datasource - Wikipedia, the free encyclopedia
A DataSource object has properties that can be modified when necessary. For example, if the data source is moved to a different server, the property ...

Inverness Graham Acquires DataSource
Inverness Graham , a lower middle market private equity firm headquartered in suburban Philadelphia, has acquired DataSource , a print supply ...

SmartGlance for iPad for iPad on the iTunes App Store
Read reviews, get customer ratings, see screenshots, and learn more about SmartGlance for iPad on the App Store. Download SmartGlance for iPad ...

Chaitanya Pandit (@chaitanyapandit) on Twitter
Sign in Sign up To bring you Twitter, we and our partners use cookies on our and other websites. Cookies help personalize Twitter content, tailor ...

Data source - Wikipedia, the free encyclopedia
... Data source A data source is any of the following types of sources for (mostly) digitized data: a database in the Java software platform, datasource ...

2ndQuadrant - PostgreSQL expertise from specialists with a source code level understanding of RDBMS ...
PostgreSQL expertise from specialists with a source code level understanding of RDBMS PostgreSQL Planets Gabriele’s PlanetPostgreSQL Gianni’s ...

Tagged entries for CLOUD COMPUTING
Alan Williamson's output as a Java Champion, Blog-City Architect, BlueDragon Creator, Author, Speaker and Internet Guru

Private equity deals
... of biometric identity management systems, applications and services. Inverness Graham Investment has acquired DataSource ...

C# C Sharp and Tutorials on C#
Learn the c# langauge to build web applications using our online tutorials with live demos. Participate in our forums and learn from others. ...

JavaScript UI Library, Ajax Components & HTML5 Framework - DHTMLX
DHTMLX offers a rich JavaScript library, UI components & HTML5 mobile framework. Build impressive web apps for both desktop and mobile devices. ...

Resources last updated: 1/7/2016 5:46:27 PM