VB.NET: CheckBoxList - programmatically setting Items as Checked - asp.net

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

Related

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

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.

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.

RangeValidator not working when selecting DropDownList value using jQuery

I inherited a site which I am in the middle of updating which has a DropDownList and a RangeValidator assigned to it. The data is bound to the dropdown on Page_Load. The values are retrieved from the database so the value property of each item is set to the unique ID of the item in the DB.
The RangeValidator looks something like:
<asp:rangevalidator id="ddRangeValidator" runat="server" ControlToValidate="ddMenu" ErrorMessage="Please select value in range" MinimumValue="1" MaximumValue="100000" Type="Integer">*</asp:rangevalidator>
I have a method which automatically populates this value in jQuery e.g.
$("#ddMenu").val("An Option");
This works, however, when I try to post the page the range validation fails. Then even if I manually select that value, or select another valid value it still won't validate. The only way to make it validate is to select non-valid value and then re-selecting a valid one.
Any ideas?
Update
Here is the data binding code:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load, Me.Load
If Not Page.IsPostBack Then
Dim ds As New DataSet()
Dim myDbObject As New myDbObject()
ds = myDbObject.ToDataSet() // retrieves all objects from the database
// store the results in a temporary view to filter
Dim dv As DataView
dv = New DataView(ds.Tables(0), "IsLive = True", "ID", DataViewRowState.CurrentRows)
Dim i As Integer = 0
ddMenu.Items.Add("Select a value")
ddMenu.Items.Item(0).Value = 0
// add all objects from filtered list into drop down menu
For i = 0 To dv.Count - 1
With ddMenu.Items
// add a new item
.Add(dv.Item(i).Item("Name"))
// set the Value property as unique ID of object
.Item(i + 1).Value = dv.Item(i).Item("ID")
End With
Next
End If
End If
Turns out it was an issue with my page loading twice...so now the issue is going to be tracking down why it is loading twice!
I guess the Range validator verifies the actual "value" of the dropdown list. May it be possible that by using jQuery to populate your dropdown the actual entry doesn't get a proper option "value"? Could you maybe post the rendered HTML code of your dropdown list?

Resources