How to add a new value to Dropdownlist - asp.net

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

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 compare row values of two gridviews with dropdownlist column in asp.net?

I have two gridviews. The first one has a dropdownlist. When a user clicks a button named 'Show' data will be displayed on both gridviews where data comes from database. The row data on column with dropdownlist must be compared to the rows on the first column of the second gridview. If they are equal a messagebox will prompt saying that there's no changes and data will not be saved, else if they are not equal modal pop-up will be displayed asking if data are correct.
Below is my code for comparing but it only reads the value of the 1st row in gridview1.
For i = 0 To GridView1.Rows.Count - 1
Dim ddl As DropDownList = DirectCast(GridView1.Rows(i).Cells(6).FindControl("dropdowncriteria"), DropDownList)
Dim txt As TextBox = DirectCast(GridView1.Rows(i).Cells(7).FindControl("txtreason"), TextBox)
If ddl.SelectedValue = GridView2.Rows(i).Cells(0).Text And txt.Text = GridView2.Rows(i).Cells(1).Text Then
MessageBox("No Changes Made! Nothing will be Saved.")
Return
Else
lblmsg.Text = "Are you sure that all the Data you've Selected/Entered are Correct?"
mdlpopupmsg.Show()
Return
End If
Next
What must be the problem on this?
Thanks in advance.
It only reads the first value (i=0) because the return statements cause the for loop to exit after the first comparison. If you want to compare all the rows you will need a variable to keep track of the result of the if test for each row. Something like this:
Dim hasChanges As Boolean = False
For i = 0 To GridView1.Rows.Count - 1
...
If ddl.SelectedValue = GridView2.Rows(i).Cells(0).Text And txt.Text = GridView2.Rows(i).Cells(1).Text Then
'do nothing
Else
hasChanges = True
End If
Next
If hasChanges Then
MessageBox("Has changes.")
Else
MessageBox("No changes.")
End If
Dim itemt As Double
If (DataGridCart.RowCount() > 0) Then
For i = 0 To DataGridCart.Rows.Count - 1
'if itemt as double
itemt = Val(Trim(txtItem.Text))
If ((DataGridCart.Rows(i).Cells("Item").Value).Equals(itemt)) Then
MsgBox("existing entry")
End If
Next
End If

ASP.NET DropDownList Selected Value With Enumeration

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.

ASP.Net - Reducing repetitive code for validation - VB

I have a form with many drop down list boxes on. Each of which I am showing or hiding a row of a table based on its value then adding a requiredfieldvalidator to the text box contained in that row. I am doing this on the selectedindexchanged event of each drop down list, the code for which can be seen below:
Protected Sub cbOffCover_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbOffCover.SelectedIndexChanged
If cbOffCover.SelectedValue = "N" Then
OffCoverRow.Visible = True
Dim rfOffcover As RequiredFieldValidator = New RequiredFieldValidator
With rfOffcover
.ControlToValidate = txtOffCover.ID
.SetFocusOnError = True
.ErrorMessage = "*"
.ForeColor = System.Drawing.Color.Red
End With
OffCoverCell.Controls.Add(rfOffcover)
Else
OffCoverRow.Visible = False
Dim c As Control
For Each c In OffCoverCell.Controls
If c.ID = "rfOffCover" Then
OffCoverCell.Controls.Remove(c)
End If
Next c
End If
End Sub
I then reuse this code for each drop down list to show/hide a differently named row and apply validation to a different text box.
My question being is there a better way of doing this? I don't know exactly how but I can't help but think I don't have to write this much code (or copy/paste) over and over again for each drop down list. Is it possible to write a function/class that will do the work and I can just call that instead? Might seem basic but i'm new to asp/vb. Many thanks
You can put it in a function that returns a boolean. When you call the function, pass it the combobox itself and whatever values you want to validate against. If it matches, return true. Try something like this:
Public Function ValidateComboBox(someComboBox as ComboBox, expectedValue as String)
Dim result as Boolean = False
If someComboBox.SelectedValue = expectedValue Then
result = True
OffCoverRow.Visible = True
Dim rfOffcover As RequiredFieldValidator = New RequiredFieldValidator
With rfOffcover
.ControlToValidate = txtOffCover.ID
.SetFocusOnError = True
.ErrorMessage = "*"
.ForeColor = System.Drawing.Color.Red
End With
OffCoverCell.Controls.Add(rfOffcover)
Else
OffCoverRow.Visible = False
Dim c As Control
For Each c In OffCoverCell.Controls
If c.ID = "rfOffCover" Then
OffCoverCell.Controls.Remove(c)
End If
Next c
End If
Return result
End Function
Of course, modify it to fit your needs. Maybe you only return the value, and do the other stuff inside the control's SelectedIndexChanged method.

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