473,687 Members | 3,552 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ASP.NET Set selected value of Dropdown within Datagrid

I have a datagrid with a template column that contains a dropdown list.
I currently fill and display the dropdown list on the page load. This is
working correctly. I am NOT using an Edit Column. I am receiving errors
when trying to set the selected value of the dropdown within the
ItemDataBound() subroutine. Below is the code I am using. I hope someone
can tell me if this is possible.

'''HTML'''

<asp:datagrid id="dgAssignmen ts" runat="server"
AutoGenerateCol umns="False">
<Columns>
<asp:TemplateCo lumn SortExpression= "PermAssignment "
HeaderText="Per manent <br> Assignment"
HeaderStyle-HorizontalAlign ="Center">
<ItemTemplate >
<asp:DropDownLi st Runat="server" ID="ddlPermanen tAssignment"
DataTextField=" DisplayName"
DataValueField= "EmployeeID "></asp:DropDownLis t>
</ItemTemplate>
</asp:TemplateCol umn>
</asp:datagrid>

'''Code Behind'''
Private Sub dgAssignments_I temDataBound(By Val sender As Object, ByVal e
As System.Web.UI.W ebControls.Data GridItemEventAr gs) Handles
dgAssignments.I temDataBound

Dim ddlPermanentAss ignment As DropDownList =
CType(e.Item.Fi ndControl("ddlP ermanentAssignm ent"), DropDownList)

Dim ddlTemporaryAss ignment As DropDownList =
CType(e.Item.Fi ndControl("ddlT emporaryAssignm ent"), DropDownList)

If e.Item.ItemType = ListItemType.Al ternatingItem OrElse e.Item.ItemType
= ListItemType.It em Then

'Retrieve Employees for Dropdown Lists
Dim GetEmployees As SqlClient.SqlCo mmand = New
SqlClient.SqlCo mmand("spvGetEm ployees", Me.DataConnecti on)
Dim DaEmployees As New SqlClient.SqlDa taAdapter
Dim dsEmp As New DataSet

GetEmployees.Co mmandType = CommandType.Sto redProcedure
GetEmployees.Pa rameters.Add("R ETURN_VALUE", SqlDbType.Int). Direction =
ParameterDirect ion.ReturnValue
DaEmployees.Sel ectCommand = GetEmployees
DaEmployees.Fil l(dsEmp)

'Load Permanent Assignment Dropdown List
ddlPermanentAss ignment.DataSou rce = dsEmp
ddlPermanentAss ignment.DataBin d()

'''ERROR OCCURS WITHIN CODE BLOCK BELOW''''
'Set Current Permanent Employee
Dim CurrentPermanen t As String = DataBinder.Eval (e.Item.DataIte m,
"EmployeeID ")
Dim liPermanent As ListItem =
ddlPermanentAss ignment.Items.F indByValue(Curr entPermanent.To String())
If Not (liPermanent Is Nothing) Then
liPermanent.Sel ected = True
End If
End If
End Sub
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 19 '05 #1
6 5394
What kind of exception you have exactly?
Can you put a breakpoint to see if CurrentPermanen t get actually a value
from the dataset?
Does the error happen to any row or just a specific one?
----------------------
Jean-Claude Morin, MCP
Software Developer
2k1Soft, Canada

"Jenna Alten" <ja****@vitale. com> wrote in message
news:eS******** ******@TK2MSFTN GP15.phx.gbl...
I have a datagrid with a template column that contains a dropdown list.
I currently fill and display the dropdown list on the page load. This is
working correctly. I am NOT using an Edit Column. I am receiving errors
when trying to set the selected value of the dropdown within the
ItemDataBound() subroutine. Below is the code I am using. I hope someone
can tell me if this is possible.

'''HTML'''

<asp:datagrid id="dgAssignmen ts" runat="server"
AutoGenerateCol umns="False">
<Columns>
<asp:TemplateCo lumn SortExpression= "PermAssignment "
HeaderText="Per manent <br> Assignment"
HeaderStyle-HorizontalAlign ="Center">
<ItemTemplate >
<asp:DropDownLi st Runat="server" ID="ddlPermanen tAssignment"
DataTextField=" DisplayName"
DataValueField= "EmployeeID "></asp:DropDownLis t>
</ItemTemplate>
</asp:TemplateCol umn>
</asp:datagrid>

'''Code Behind'''
Private Sub dgAssignments_I temDataBound(By Val sender As Object, ByVal e
As System.Web.UI.W ebControls.Data GridItemEventAr gs) Handles
dgAssignments.I temDataBound

Dim ddlPermanentAss ignment As DropDownList =
CType(e.Item.Fi ndControl("ddlP ermanentAssignm ent"), DropDownList)

Dim ddlTemporaryAss ignment As DropDownList =
CType(e.Item.Fi ndControl("ddlT emporaryAssignm ent"), DropDownList)

If e.Item.ItemType = ListItemType.Al ternatingItem OrElse e.Item.ItemType
= ListItemType.It em Then

'Retrieve Employees for Dropdown Lists
Dim GetEmployees As SqlClient.SqlCo mmand = New
SqlClient.SqlCo mmand("spvGetEm ployees", Me.DataConnecti on)
Dim DaEmployees As New SqlClient.SqlDa taAdapter
Dim dsEmp As New DataSet

GetEmployees.Co mmandType = CommandType.Sto redProcedure
GetEmployees.Pa rameters.Add("R ETURN_VALUE", SqlDbType.Int). Direction =
ParameterDirect ion.ReturnValue
DaEmployees.Sel ectCommand = GetEmployees
DaEmployees.Fil l(dsEmp)

'Load Permanent Assignment Dropdown List
ddlPermanentAss ignment.DataSou rce = dsEmp
ddlPermanentAss ignment.DataBin d()

'''ERROR OCCURS WITHIN CODE BLOCK BELOW''''
'Set Current Permanent Employee
Dim CurrentPermanen t As String = DataBinder.Eval (e.Item.DataIte m,
"EmployeeID ")
Dim liPermanent As ListItem =
ddlPermanentAss ignment.Items.F indByValue(Curr entPermanent.To String())
If Not (liPermanent Is Nothing) Then
liPermanent.Sel ected = True
End If
End If
End Sub
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 19 '05 #2
When I walk through the code it gets past the first line of code:
Dim CurrentPermanen t As String = DataBinder.Eval (e.Item.DataIte m,
"EmployeeID ")

But if I check the value for CurrentPermanen t, it is Nothing.

Then I get the following exception on the second line of code:
Object reference not set to an instance of an object.

Have you done this before? All the examples I've seen have been for the
Edit Column, is this possible??

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 19 '05 #3
Hi Jenna,

These guys have excellent examples of how to do what you need.

http://aspnet.4guysfromrolla.com/articles/040502-1.aspx

I used alot of what they recommended and here's how I set values for
dropdownlists in my datagrid (also not edit columns) I''ve taken out
some of the code to shorten the example (...).

The function that fills the dropdown and sets the selected value is
called "GetOverallRati ngs" and is located in the code behind but called
from the VB Script function ComputeSum in the HTML. The ComputeSum
function is called from the datagrid like this:
OnItemDataBound ="ComputeSum "
HTML
---------
<script language="VB" runat="server">
Dim proposedSum as Decimal = CDec(0)
Dim currentSum as Decimal = CDec(0)

'************** *************** ************
' Compute sums/set footers
'************** *************** ************
Sub ComputeSum(send er As Object, e As DataGridItemEve ntArgs)
dim CPL as double = cdbl(lblCPL.Tex t)

If e.Item.ItemType = ListItemType.It em OR e.Item.ItemType =
ListItemType.Al ternatingItem OR e.Item.ItemType = ListItemType.Ed itItem
then ' Item, AlternatingItem , or Edit Item
Dim proposedPay as Decimal = CDec(DataBinder .Eval(e.Item.Da taItem,
"ProposedPa y"))
Dim currentPay as Decimal = CDec(DataBinder .Eval(e.Item.Da taItem,
"CurrentPay "))

...

proposedSum += proposedPay
currentSum += currentPay

GetOverallRatin gs(e, DataBinder.Eval (e.Item.DataIte m,
"OverallRating" ))
ElseIf e.Item.ItemType = ListItemType.Fo oter then ' Footer
Dim totalAvailable as double = cdbl(Math.Round (currentSum *
(CPL/100), 2))
dim currentTotal as double = cdbl(Math.Round (proposedSum -
currentSum, 2))

e.Item.Cells(7) .Text = Format(currentS um, "Currency")
e.Item.Cells(9) .Text = Format(proposed Sum, "Currency")

...
End If
End Sub
</script>
....
<asp:DataGrid id="dgIncreases " runat="server" ShowFooter="Tru e"
OnItemDataBound ="ComputeSum " ...>

....
<asp:TemplateCo lumn HeaderText="Ove rall<br>Rating" >
<ItemTemplate >
<asp:DropDownLi st ID="cboOverallR ating" AutoPostBack="F alse"
Runat="server"> </asp:DropDownLis t>
</ItemTemplate>
</asp:TemplateCol umn>

CODE BEHIND
----------------------

Sub GetOverallRatin gs(ByVal e As DataGridItemEve ntArgs, ByVal
rating As String)
Try
Dim cboOverallRatin g As DropDownList =
CType(e.Item.Fi ndControl("cboO verallRating"), DropDownList)
If Not cboOverallRatin g Is Nothing Then

' Populate Overall Ratings
...

' Select the Rating
Dim li As ListItem =
cboOverallRatin g.Items.FindByV alue(rating)
If (Not li Is Nothing) Then
li.Selected = True
End If
End If
Catch ex As Exception
lblErrorMessage .Text = ex.Message
End Try
I hope this helps.

Michelle

Nov 19 '05 #4
Thank you so much Michelle, this really looks like it's going to work.
One question, what is the 'OverallRating' value in the following code:

GetOverallRatin gs(e, DataBinder.Eval (e.Item.DataIte m,
"OverallRating" ))
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 19 '05 #5
Overall Rating is just a rating that is given to a person like: E =
Excellent, NI = Needs Improvement. I send what the value is for that
associate to the GetOverallRatin gs function using
DataBinder.Eval (e.Item.DataIte m, "OverallRating" ) so that it knows what
rating to select for him/her (if one has already exists in the database
for that person).

I hope that made sense!
Michelle

Nov 19 '05 #6
I use code like this for cbos in my datagrid ItemDataBound event.
Find the control, set its source and properties and then bind it and then
set the value.
=============== =============== =============== ===============
Dim locboFldrule As DropDownList =
CType(e.Item.Fi ndControl("cboF ldrule"), DropDownList)

locboFldrule.Da taSource = mLineItem.Valru lesNVL.Bindable List
locboFldrule.Da taTextField = "Value"
locboFldrule.Da taValueField = "Key"
locboFldrule.Da taBind()
locboFldrule.Se lectedValue = CStr(...)
=============== =============== =============== ===============
When unbinding the grid I use code like this:

Dim locboFldrule As DropDownList =
CType(dgi.FindC ontrol("cboFldr ule"), DropDownList)

'when no rule is assigned then SelectedIndex = -1 so do not unbind.
If locboFldrule.Se lectedIndex >= 0 Then
mLineItem.fldru le = CDec(locboFldru le.SelectedValu e)
End If

--
Joe Fallon


"Jenna Alten" <ja****@vitale. com> wrote in message
news:eS******** ******@TK2MSFTN GP15.phx.gbl...
I have a datagrid with a template column that contains a dropdown list.
I currently fill and display the dropdown list on the page load. This is
working correctly. I am NOT using an Edit Column. I am receiving errors
when trying to set the selected value of the dropdown within the
ItemDataBound() subroutine. Below is the code I am using. I hope someone
can tell me if this is possible.

'''HTML'''

<asp:datagrid id="dgAssignmen ts" runat="server"
AutoGenerateCol umns="False">
<Columns>
<asp:TemplateCo lumn SortExpression= "PermAssignment "
HeaderText="Per manent <br> Assignment"
HeaderStyle-HorizontalAlign ="Center">
<ItemTemplate >
<asp:DropDownLi st Runat="server" ID="ddlPermanen tAssignment"
DataTextField=" DisplayName"
DataValueField= "EmployeeID "></asp:DropDownLis t>
</ItemTemplate>
</asp:TemplateCol umn>
</asp:datagrid>

'''Code Behind'''
Private Sub dgAssignments_I temDataBound(By Val sender As Object, ByVal e
As System.Web.UI.W ebControls.Data GridItemEventAr gs) Handles
dgAssignments.I temDataBound

Dim ddlPermanentAss ignment As DropDownList =
CType(e.Item.Fi ndControl("ddlP ermanentAssignm ent"), DropDownList)

Dim ddlTemporaryAss ignment As DropDownList =
CType(e.Item.Fi ndControl("ddlT emporaryAssignm ent"), DropDownList)

If e.Item.ItemType = ListItemType.Al ternatingItem OrElse e.Item.ItemType
= ListItemType.It em Then

'Retrieve Employees for Dropdown Lists
Dim GetEmployees As SqlClient.SqlCo mmand = New
SqlClient.SqlCo mmand("spvGetEm ployees", Me.DataConnecti on)
Dim DaEmployees As New SqlClient.SqlDa taAdapter
Dim dsEmp As New DataSet

GetEmployees.Co mmandType = CommandType.Sto redProcedure
GetEmployees.Pa rameters.Add("R ETURN_VALUE", SqlDbType.Int). Direction =
ParameterDirect ion.ReturnValue
DaEmployees.Sel ectCommand = GetEmployees
DaEmployees.Fil l(dsEmp)

'Load Permanent Assignment Dropdown List
ddlPermanentAss ignment.DataSou rce = dsEmp
ddlPermanentAss ignment.DataBin d()

'''ERROR OCCURS WITHIN CODE BLOCK BELOW''''
'Set Current Permanent Employee
Dim CurrentPermanen t As String = DataBinder.Eval (e.Item.DataIte m,
"EmployeeID ")
Dim liPermanent As ListItem =
ddlPermanentAss ignment.Items.F indByValue(Curr entPermanent.To String())
If Not (liPermanent Is Nothing) Then
liPermanent.Sel ected = True
End If
End If
End Sub
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 19 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

24
77368
by: London | last post by:
Hello Can you help me. By ASP How can I get the dropdown(control'name)'s selected value? What is it's property'name?
5
2658
by: DC Gringo | last post by:
I have a dropdownlist that, upon form submission, I'd like to maintain the selected value when I get my result...how do I do that? <asp:dropdownlist Font-Size="8" id="ddlCommunities" runat="server" Width="100"></asp:dropdownlist> Sub RunReport_OnClick(sender As Object, e As System.EventArgs) _sqlStmt &= " AND tblSurvey1.clnGUID = '" &
5
10828
by: Kris Rockwell | last post by:
Hello (again), I have gotten the dropdown list functionality to work through a few tricks (probably not the most efficient, but it works) but I am not sure how to set the default selected value. I have tried setting various values to represent the default value with little success. Essentially I am looking to have the first item in the list be the default selected item. I noticed in the properties for a dtat grid you could set a default...
0
1140
by: Tim::.. | last post by:
Hi, I'm trying to create a function that will show the current value of a datagrid when you go into the edit mode of the datagrid. At the moment when ever I hit edit it just shows me a list of values in the dropdown list with the default selected value always chosen, rather than the actual value shown in the datagrid. I would really appritiate any help!
6
1343
by: Tan | last post by:
Hello Everyone Need help! I have a object with the integer property that represent the address type. I like to show a combo box in the grid linked to an object data source displaying the string value instead of integer value. any help would very much appriciated Tan
1
1485
by: vishnu | last post by:
Hi, I have a fully editable datagrid which has dropdownlist in two columns. Now i have to bind the dropdown in the second column based on the value selected in the dropdown in the firstcolumn. so how to do it. I am able to raise the selected index changed event of the dropdowns in the first column, but i am not able to get the reference for the dropdown in the corresponding row. Regards, Vishnucharan.
1
10391
by: Ben | last post by:
I have a formview with a few dropdownlists (software version, database version, etc). When a software version is selected, the database version dropdownlist updates itself accordingly. When in edit mode, everything works fine - the selected value in each list defaults to the value from the database record (selectedvalue=bind...). However, in insert mode (insertitem), it is not working. I pass in a value on the query string that I would...
6
5848
by: yasodhai | last post by:
Hi, I used a dropdown control which is binded to a datagrid control. I passed the values to the dropdownlist from the database using a function as follows in the aspx itself. <asp:DropDownList ID="FldType_add" Runat="server" DataSource='< %#GetFieldType()%>' DataValueField="Type" DataTextField="Type" /> Oce the page is loaded all the values are added to the dropdown list. But when I thought of getting the selected value from the...
2
2127
by: yasodhai | last post by:
Hi, I used a dropdown control bind to a datagrid. <EditItemTemplate> <asp:DropDownList ID="FldType_edit" Runat="server" DataSource='< %#GetFieldType()%>' DataTextField="Type" /> </EditItemTemplate> The values for the datagrid are retrieved from the database using the GetFieldType function
0
8528
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9072
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8947
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8786
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7621
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6453
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4321
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2964
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
1950
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.