469,651 Members | 1,676 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,651 developers. It's quick & easy.

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="dgAssignments" runat="server"
AutoGenerateColumns="False">
<Columns>
<asp:TemplateColumn SortExpression="PermAssignment"
HeaderText="Permanent <br> Assignment"
HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:DropDownList Runat="server" ID="ddlPermanentAssignment"
DataTextField="DisplayName"
DataValueField="EmployeeID"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</asp:datagrid>

'''Code Behind'''
Private Sub dgAssignments_ItemDataBound(ByVal sender As Object, ByVal e
As System.Web.UI.WebControls.DataGridItemEventArgs) Handles
dgAssignments.ItemDataBound

Dim ddlPermanentAssignment As DropDownList =
CType(e.Item.FindControl("ddlPermanentAssignment") , DropDownList)

Dim ddlTemporaryAssignment As DropDownList =
CType(e.Item.FindControl("ddlTemporaryAssignment") , DropDownList)

If e.Item.ItemType = ListItemType.AlternatingItem OrElse e.Item.ItemType
= ListItemType.Item Then

'Retrieve Employees for Dropdown Lists
Dim GetEmployees As SqlClient.SqlCommand = New
SqlClient.SqlCommand("spvGetEmployees", Me.DataConnection)
Dim DaEmployees As New SqlClient.SqlDataAdapter
Dim dsEmp As New DataSet

GetEmployees.CommandType = CommandType.StoredProcedure
GetEmployees.Parameters.Add("RETURN_VALUE", SqlDbType.Int).Direction =
ParameterDirection.ReturnValue
DaEmployees.SelectCommand = GetEmployees
DaEmployees.Fill(dsEmp)

'Load Permanent Assignment Dropdown List
ddlPermanentAssignment.DataSource = dsEmp
ddlPermanentAssignment.DataBind()

'''ERROR OCCURS WITHIN CODE BLOCK BELOW''''
'Set Current Permanent Employee
Dim CurrentPermanent As String = DataBinder.Eval(e.Item.DataItem,
"EmployeeID")
Dim liPermanent As ListItem =
ddlPermanentAssignment.Items.FindByValue(CurrentPe rmanent.ToString())
If Not (liPermanent Is Nothing) Then
liPermanent.Selected = 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 5158
What kind of exception you have exactly?
Can you put a breakpoint to see if CurrentPermanent 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**************@TK2MSFTNGP15.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="dgAssignments" runat="server"
AutoGenerateColumns="False">
<Columns>
<asp:TemplateColumn SortExpression="PermAssignment"
HeaderText="Permanent <br> Assignment"
HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:DropDownList Runat="server" ID="ddlPermanentAssignment"
DataTextField="DisplayName"
DataValueField="EmployeeID"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</asp:datagrid>

'''Code Behind'''
Private Sub dgAssignments_ItemDataBound(ByVal sender As Object, ByVal e
As System.Web.UI.WebControls.DataGridItemEventArgs) Handles
dgAssignments.ItemDataBound

Dim ddlPermanentAssignment As DropDownList =
CType(e.Item.FindControl("ddlPermanentAssignment") , DropDownList)

Dim ddlTemporaryAssignment As DropDownList =
CType(e.Item.FindControl("ddlTemporaryAssignment") , DropDownList)

If e.Item.ItemType = ListItemType.AlternatingItem OrElse e.Item.ItemType
= ListItemType.Item Then

'Retrieve Employees for Dropdown Lists
Dim GetEmployees As SqlClient.SqlCommand = New
SqlClient.SqlCommand("spvGetEmployees", Me.DataConnection)
Dim DaEmployees As New SqlClient.SqlDataAdapter
Dim dsEmp As New DataSet

GetEmployees.CommandType = CommandType.StoredProcedure
GetEmployees.Parameters.Add("RETURN_VALUE", SqlDbType.Int).Direction =
ParameterDirection.ReturnValue
DaEmployees.SelectCommand = GetEmployees
DaEmployees.Fill(dsEmp)

'Load Permanent Assignment Dropdown List
ddlPermanentAssignment.DataSource = dsEmp
ddlPermanentAssignment.DataBind()

'''ERROR OCCURS WITHIN CODE BLOCK BELOW''''
'Set Current Permanent Employee
Dim CurrentPermanent As String = DataBinder.Eval(e.Item.DataItem,
"EmployeeID")
Dim liPermanent As ListItem =
ddlPermanentAssignment.Items.FindByValue(CurrentPe rmanent.ToString())
If Not (liPermanent Is Nothing) Then
liPermanent.Selected = 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 CurrentPermanent As String = DataBinder.Eval(e.Item.DataItem,
"EmployeeID")

But if I check the value for CurrentPermanent, 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 "GetOverallRatings" 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(sender As Object, e As DataGridItemEventArgs)
dim CPL as double = cdbl(lblCPL.Text)

If e.Item.ItemType = ListItemType.Item OR e.Item.ItemType =
ListItemType.AlternatingItem OR e.Item.ItemType = ListItemType.EditItem
then ' Item, AlternatingItem, or Edit Item
Dim proposedPay as Decimal = CDec(DataBinder.Eval(e.Item.DataItem,
"ProposedPay"))
Dim currentPay as Decimal = CDec(DataBinder.Eval(e.Item.DataItem,
"CurrentPay"))

...

proposedSum += proposedPay
currentSum += currentPay

GetOverallRatings(e, DataBinder.Eval(e.Item.DataItem,
"OverallRating"))
ElseIf e.Item.ItemType = ListItemType.Footer 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(currentSum, "Currency")
e.Item.Cells(9).Text = Format(proposedSum, "Currency")

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

....
<asp:TemplateColumn HeaderText="Overall<br>Rating">
<ItemTemplate>
<asp:DropDownList ID="cboOverallRating" AutoPostBack="False"
Runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>

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

Sub GetOverallRatings(ByVal e As DataGridItemEventArgs, ByVal
rating As String)
Try
Dim cboOverallRating As DropDownList =
CType(e.Item.FindControl("cboOverallRating"), DropDownList)
If Not cboOverallRating Is Nothing Then

' Populate Overall Ratings
...

' Select the Rating
Dim li As ListItem =
cboOverallRating.Items.FindByValue(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:

GetOverallRatings(e, DataBinder.Eval(e.Item.DataItem,
"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 GetOverallRatings function using
DataBinder.Eval(e.Item.DataItem, "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.FindControl("cboFldrule"), DropDownList)

locboFldrule.DataSource = mLineItem.ValrulesNVL.BindableList
locboFldrule.DataTextField = "Value"
locboFldrule.DataValueField = "Key"
locboFldrule.DataBind()
locboFldrule.SelectedValue = CStr(...)
================================================== ==========
When unbinding the grid I use code like this:

Dim locboFldrule As DropDownList =
CType(dgi.FindControl("cboFldrule"), DropDownList)

'when no rule is assigned then SelectedIndex = -1 so do not unbind.
If locboFldrule.SelectedIndex >= 0 Then
mLineItem.fldrule = CDec(locboFldrule.SelectedValue)
End If

--
Joe Fallon


"Jenna Alten" <ja****@vitale.com> wrote in message
news:eS**************@TK2MSFTNGP15.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="dgAssignments" runat="server"
AutoGenerateColumns="False">
<Columns>
<asp:TemplateColumn SortExpression="PermAssignment"
HeaderText="Permanent <br> Assignment"
HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:DropDownList Runat="server" ID="ddlPermanentAssignment"
DataTextField="DisplayName"
DataValueField="EmployeeID"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</asp:datagrid>

'''Code Behind'''
Private Sub dgAssignments_ItemDataBound(ByVal sender As Object, ByVal e
As System.Web.UI.WebControls.DataGridItemEventArgs) Handles
dgAssignments.ItemDataBound

Dim ddlPermanentAssignment As DropDownList =
CType(e.Item.FindControl("ddlPermanentAssignment") , DropDownList)

Dim ddlTemporaryAssignment As DropDownList =
CType(e.Item.FindControl("ddlTemporaryAssignment") , DropDownList)

If e.Item.ItemType = ListItemType.AlternatingItem OrElse e.Item.ItemType
= ListItemType.Item Then

'Retrieve Employees for Dropdown Lists
Dim GetEmployees As SqlClient.SqlCommand = New
SqlClient.SqlCommand("spvGetEmployees", Me.DataConnection)
Dim DaEmployees As New SqlClient.SqlDataAdapter
Dim dsEmp As New DataSet

GetEmployees.CommandType = CommandType.StoredProcedure
GetEmployees.Parameters.Add("RETURN_VALUE", SqlDbType.Int).Direction =
ParameterDirection.ReturnValue
DaEmployees.SelectCommand = GetEmployees
DaEmployees.Fill(dsEmp)

'Load Permanent Assignment Dropdown List
ddlPermanentAssignment.DataSource = dsEmp
ddlPermanentAssignment.DataBind()

'''ERROR OCCURS WITHIN CODE BLOCK BELOW''''
'Set Current Permanent Employee
Dim CurrentPermanent As String = DataBinder.Eval(e.Item.DataItem,
"EmployeeID")
Dim liPermanent As ListItem =
ddlPermanentAssignment.Items.FindByValue(CurrentPe rmanent.ToString())
If Not (liPermanent Is Nothing) Then
liPermanent.Selected = 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 discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by DC Gringo | last post: by
5 posts views Thread by Kris Rockwell | last post: by
reply views Thread by Tim::.. | last post: by
6 posts views Thread by Tan | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.