ASP.NET DropDownList Selected Value With Enumeration - asp.net

I'm using the settings in an enumeration to populate a dropdownlist in ASP.NET 4.0. The problem I'm having is that when I attempt to set a selected value other than first item, it throws an error telling me it cannot have more than one option selected.
Here's a sample of the code:
Public Shared Function ConvertEnumToArray(ByVal enumType As System.Type, _
Optional ByVal DefaultValue As String = "nodefault", _
Optional ByVal PromptValue As String = "", _
Optional ByVal PromptText As String = "") As ListItem()
Dim itemSelected As Boolean = False
Dim i As Int32 = 0
If Not enumType.IsEnum Then
Throw New Exception(String.Format("Type {0} is not an enumeration.", enumType.Name))
End If
'Dim itemValues() As Array = [Enum].GetValues(enumType)
Dim fields As FieldInfo() = enumType.GetFields()
Dim itemNames() As String = [Enum].GetNames(enumType)
Dim arr(itemNames.Length + 1) As ListItem
For Each field As FieldInfo In fields
If Not field.Name.Equals("value__") Then
Dim item As New ListItem(field.Name, field.GetRawConstantValue().ToString())
If item.Value = DefaultValue And DefaultValue <> "nodefault" Then
item.Selected = True
itemSelected = True
End If
arr(i) = item
i = i + 1
End If
Next
If PromptText <> "" Then
Dim item As New ListItem(PromptText, PromptValue)
If Not itemSelected Then
item.Selected = True
End If
arr(i) = item
End If
Return arr
End Function
Dim arrExtraChargesOptions() As ListItem
arrExtraChargesOptions = Enumerations.ConvertEnumToArray(GetType(Enumerations.MoneyRoomCourierExtraChargesOptions))
For Each li As ListItem In arrExtraChargesOptions
'since arrays double in capacity to store data, there may be nulls
If Not li Is Nothing Then
Me.drpMondayExtraCharges.Items.Add(li)
End If
Next
Me.drpMondayExtraCharges.ClearSelection()
Me.drpMondayExtraCharges.SelectedIndex = -1
Me.drpMondayExtraCharges.Items.FindByValue(Courier.MondayExtraCharge.ToString()).Selected = True
Despite clearing the selected value in multiple ways, the first item remains selected resulting in the error as mentioned above.
Other items that might help explaining how I ended up with the code above:
I'm setting the return type of the function to an array since that's the parameter type the AddRange function on the DropdownList.Items expects, but when I used that method, an exception resulted due to the NULLs in the array.
Before adding the ClearSelection() and SelectedIndex = -1 lines, my setting the selected value (either through the FindByValue as above or just directly setting the SelectedValue) resulted in my desired selected value being ignored.
Any thoughts? Thanks.
EDIT: I misspoke above (bad memory): Setting the SelectedValue directly results is what results in it being ignored. It has nothing to do with ClearSelection Or SelectedIndex =1 as I stated in the second bullet up above.

I found this issue (and I didn't provide enough code for you to find it yourselves).
Basically, I had a dropdownlist for each day of the week and the list items returned by ConvertEnumToArray above were added to each of the dropdowns. As a result, the selected item was changed on all the dropdown since the same list items were on each dropdown. Adding them to the dropdown as New Listitems solved the problem.

Related

VB.NET: CheckBoxList - programmatically setting Items as Checked

I pass in comma separated values to this function, and check items in a checkboxlist according to the values. But there are no items checked after the function call.
For example, I pass in a string "1,5,8", hoping the 3 items with value of 1,5,8 in the checkboxlist will get "checked = true" status. But they don't.
Private Sub GetListValuesFromCommaSeparatedValueString(ByRef lst As CheckBoxList, s As String)
If IsNothing(s) Or s = "" Then
Exit Sub
End If
Dim array = s.Split(",")
For Each value As String In array
lst.Items.FindByValue(value).Selected = True
Next
End Sub
You'd want the Checked property of CheckBox not Selected.
For Each value As String In array
lst.Items.FindByValue(value).Checked = True
Next
More info on Checked.
You should use checked property, selected highlights only certain item on list
lst.Items.FindByValue(value).Checked = True

How to add a new value to Dropdownlist

I am loading datasource to Dropdown list and binding, but in some scenario new value is coming (case sensitive) so i cannot able to set as selected value for the drop downlist?
How to acheive this, means to show the datagrid selected value as text in drop down list?
Populating data into dropdown list
Me.RmtRouterName.DataSource = Me.datareader_1param("pr_list_dev_by_site",
SiteID, "#enter_value")
Me.RmtRouterName.DataTextField = "devname"
Me.RmtRouterName.DataValueField = "devname"
Reading value from datagrid
tmpstr = MyIIF(Me.SiteInfo1.Tables(SiteInfoTableName).Rows(0), "RmtRouterName")
If (tmpstr = String.Empty) Then
Me.RmtRouterName.SelectedIndex = -1
Else
Me.RmtRouterName.SelectedValue = tmpstr
in some cases the datareader values and datgrid values are mismatching (due to case sensitive) how to overcome this problem
In your Else logic, attempt to find the text value in the drop down list before attempting to set the SelectedValue, like this:
Helper Function:
Public Function FindByTextCaseInsensitive(ByVal ctl As ListControl, ByVal text As String) As ListItem
If ctl Is Nothing Then
Return Nothing
End If
For Each li As ListItem In ctl.Items
If String.Compare(li.Text, text, True) = 0 Then
Return li
End If
Next
Return Nothing
End Function
Now in your Else block, do this:
Else
Dim foundItem As ListItem = FindByTextCaseInsensitive(tmpstr)
If foundItem Is Nothing Then
Me.RmtRouterName.SelectedIndex = -1
Else
Me.RmtRouterName.SelectedValue = tmpstr
End If
End If

add dataitem(from string array) to listview

To preface this, I've looked through several of the postings containing listviews and nothing really is comparing to what I'm trying to do.
I'm trying to take values determined through a loop that has several If Statements similar to what follows:
If Convert.ToInt32(GetData(ds.Tables("HRIS").Rows(i), "ABS_CO_RULE_DAYS", DefaultValue)) > 0 Or _
Convert.ToInt32(GetData(ds.Tables("HRIS").Rows(i), "ABS_CO_RULE_HRS", DefaultValue)) > 0 Or _
Convert.ToInt32(GetData(ds.Tables("HRIS").Rows(i), "ABS_CO_RULE_MINS", DefaultValue)) > 0 Then
msChargeDays = GetData(ds.Tables("HRIS").Rows(i), "ABS_CO_RULE_DAYS", DefaultValue)
msChargeHours = GetData(ds.Tables("HRIS").Rows(i), "ABS_CO_RULE_HRS", DefaultValue)
msChargeMins = GetData(ds.Tables("HRIS").Rows(i), "ABS_CO_RULE_MINS", DefaultValue)
msHowPaid = "CR DAYS"
AbsenceLine() 'calls sub
End If
This block of code returns valid results from the dataset that it calls from. Now in the following code block, I am trying to assimilate values that are determined by the main code block which is about 40 if statements similar in structure to the block above, all contained within a For loop.
In the following code block I am trying to insert an object of ListViewItem type into the ListView. This is where I'm getting my error denoted by comment string following it. The function that fills the ListViewItem is at the bottom, all of the variables returned are all class variables and return valid values to the ListViewItem. I have double checked this via the debugger.
Private Sub AbsenceLine()
Dim sTypeReason As String
If msType = "" Then
sTypeReason = Left(msReason, 25)
Else
sTypeReason = msType & "--" & msReason
End If
Dim item As ListViewItem
item = New ListViewItem(ListViewItemType.DataItem)
item.DataItem = FillListView(sTypeReason)
absence_lv.Items.Add(item) 'this line here is what is givine me issues
End Sub
Private Function FillListView(typeReason As String) As IEnumerable(Of String)
Return {msDate, msVoid, msCont, msDays, msHours, msMinutes, typeReason, msChargeDays, msChargeHours,
msChargeMins, msHowPaid} 'all values returned are of String type
End Function
Now with the background:
Am I completely off base with what I'm trying to do?
Is there an easier way to do this with a gridview instead?
I think you're misusing the DataItem property of the ListViewItem class. That's really used to get the underlying object that the ListViewItem represents when the ListView itself is bound.
Since your FillListView function is returning an IEnumerable(Of String), you can just set the ListView's DataSource property to the function call.
absence_lv.Datasource = FillListView(sTypeReason)
absence_lv.Databind()
As you can see, there is no need to manually add each item.

Changing DropDown Selected Item Based on Selected Value (ASP.NET)

I have a dropdown list on my page (ddlProgram) which is populated via a database query like so:
Using dbContext as IRFEntities = New IRFEntities
Dim getPrograms = (From p in dbContext.IRF_Program _
Order By p.name _
Select p)
ddlProgram.DataSource = getPrograms
ddlProgram.DataTextField = "name"
ddlProgram.DataValueField = "id"
ddl.Program.DataBind()
End Using
So, for example, one might have a DataTextField of "Education" and an ID of "221".
Now, I prepopulate the form with information about the individual visiting the site (if available) - including the dropdown list like so:
If getProspect IsNot Nothing Then
If getProspect.user_id Is Nothing Then
ddlProgram.SelectedValue = getProspect.Program
End If
End If
The Program property contains a number that matches the ID of a Program. So, for example, this individual might have a Program of "221" which would match the "221" of Education mentioned above.
Currently the application successfully sets the SelectedValue to "221" for the DropDownList (ddlProgram), but the SelectedItem of the DDL remains the same (e.g., if it is initially "History" with an ID of "1" after the prepopulation it is "History" with an ID of "221").
What I'm trying to make happen is that the SelectedItem is updated to item which corresponds with the SelectedValue. So, in the end, if the individual has "221" for "Education" selected when the form is prepopulated they would see Education as the selected item and the selected value would be set correctly, whereas right now the form is showing the wrong SelectedItem but has the right SelectedValue behind the scenes.
Here is a more complete idea of the code flow from the Page_Load event:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack = False Then
' If prospect is coming from unique url
Dim prospect_url As String = Page.RouteData.Values("value")
' Save prospect_url into session variable
Session("prospect_url") = prospect_url
Using dbContext As IRFEntities = New IRFEntities
' Prepopulate the programs dropdown.
Dim getPrograms = (From p In dbContext.IRF_Program _
Order By p.name _
Select p)
ddlProgram.DataSource = getPrograms
ddlProgram.DataTextField = "name"
ddlProgram.DataValueField = "id"
ddlProgram.DataBind()
End Using
Using dbContext As IRFEntities = New IRFEntities
' Prepopulate the states dropdown.
Dim getStates = (From p In dbContext.IRF_States _
Order By p.name _
Select p)
ddlState.DataSource = getStates
ddlState.DataTextField = "name"
ddlState.DataValueField = "id"
ddlState.DataBind()
End Using
Using dbContext As IRFEntities = New IRFEntities
' Grab info. about prospect based on unique url.
Dim getProspect = (From p In dbContext.IRF_Prospects _
Where p.url = prospect_url _
Select p).FirstOrDefault
' If they have a record...
If getProspect IsNot Nothing Then
If getProspect.user_id Is Nothing Then
' Prepopulate the form with their information.
' These must have a value, so we need to make sure that no column is null in the database.
ddlProgram.SelectedValue = getProspect.program
txtFirst.Text = getProspect.first_name
txtLast.Text = getProspect.last_name
txtAddress.Text = getProspect.address
txtCity.Text = getProspect.city
ddlState.SelectedValue = getProspect.state
txtZip.Text = getProspect.zip
txtPhone.Text = getProspect.phone
txtEmail.Text = getProspect.email_address
txtYearEnrolling.Text = getProspect.enrolling_in
Else
' Redirect them to login.
Response.Redirect("login.aspx")
End If
End If
End Using
End If
End Sub
What you're doing looks like it should work. If you put a breakpoint after the setting of the value and check the SelectedItem text and value, do they appear as expected or mismatched?
Use the Immediate Window to check:
ddlProgram.SelectedItem.Text
ddlProgram.SelectedItem.Value
If they appear the same then I would presume the binding code is being refired and the list is being regenerated with the first item being selected.
To check this put a break point on the binding code and see if it is fired more than once and correct the order of the methods appropriately.
ADDED:
If it works on your local environment it should work when published, if the code is the same? Looking at your code, I'd start by seperating out some of the databinding code into seperate methods rather than have everything in Page_Load, one becuase it's good practice and two because it will make debugging easier. Further than that I'm not sure what else to suggest.

Programatically created ASP.NET TextBox retains Text value after PostBack even if Control is cleared

I have a drop down menu, and based on which item is selected, I call a web service and then dynamically create some text boxes.
The first time I drop down the menu and select an item, it works perfectly, and the text boxes are created and populated dynamically. However, the next time I drop down the menu (after the first postback), and select something different... after the second postback, the original values remain in the textboxes.
I am clearing all of the text boxes out of the placeholder, then re-creating them, and then setting a NEW value, how can they retain the OLD values... especially if I controls.clear them from the page?
Note: The second time they are being created, the textbox IDs DO end up being the same. Could that have something to do with it? This duplicate ID functionality will need to be supported.
My code, called from Page_Load, is as follows: (edited to add more code)
Private Sub RefreshEntity()
Dim XmlRecords As New XmlDocument
Dim XmlRecordsNode As XmlNode
Dim EntityType As String = EntityTypes.SelectedValue
Dim Entity As String = RecordValue.Value
Dim FieldName As String
Dim FieldValue As String
FieldPlaceHolder.Controls.Clear()
If RecordList.SelectedValue <> "Select..." Then
Try
XmlRecordsNode = LoginInfo.SharePointConnectWebService.GetMetaData(LoginInfo.WSUser, LoginInfo.WSPass, _
EntityType, Entity)
XmlRecords.LoadXml(XmlRecordsNode.OuterXml)
Catch ex As Exception
ConfirmLabel.Text = "<b>Error:</b><br>" & ex.Message.ToString
Return
End Try
Else
SetProperties.Visible = False
Return
End If
For Each OneNode As XmlNode In XmlRecords.SelectNodes("Fields").Item(0).ChildNodes
FieldName = OneNode.Name
FieldValue = OneNode.InnerText
Dim newLabel As Label = New Label()
newLabel.Text = FieldName & ": "
Dim newTextBox As TextBox = New TextBox()
newTextBox.ID = "Field-" & FieldName
newTextBox.Text = FieldValue
Dim newLine As Label = New Label()
newLine.Text = "<br><br>"
FieldPlaceHolder.Controls.Add(newLabel)
FieldPlaceHolder.Controls.Add(newTextBox)
FieldPlaceHolder.Controls.Add(newLine)
Next
SetProperties.Visible = True
End Sub
And the RecordValue.Value is a hidden field that gets populated in every Page_Load:
RecordValue.Value = RecordList.SelectedValue
Where RecordList is my DropDown menu.
This is likely due to ViewState or the Posted values clobbering your values.
Once a control is dynamically added to the controls collection it needs to catch up with all the page life cycle events that have already fired. In the case of a post back this means that the ViewState and/or the posted form value will clobber the .text property on the TextBox based on the order you're adding the dynamic controls to the controls collection and setting the .text property.
To fix this you can disable ViewState by setting the .EnableViewState property to false on the dynamically generate controls also add the controls to the controls collection before you set any properties on them.
For Each OneNode As XmlNode In XmlRecords.SelectNodes("Fields").Item(0).ChildNodes
FieldName = OneNode.Name
FieldValue = OneNode.InnerText
Dim newLabel As Label = New Label()
Dim newTextBox As TextBox = New TextBox()
Dim newLine As Label = New Label()
newTextBox.ID = "Field-" & FieldName
newLabel.EnableViewState = False
newTextBox.EnableViewState = False
newLine.EnableViewState = False
FieldPlaceHolder.Controls.Add(newLabel)
FieldPlaceHolder.Controls.Add(newTextBox)
FieldPlaceHolder.Controls.Add(newLine)
newLabel.Text = FieldName & ": "
newTextBox.Text = FieldValue
newLine.Text = "<br><br>"
Next
You're not storing the value in a Session variable and then putting it back into the text box later in your code?

Resources