Stop radio button change - asp.net

I have radio button list that calls a function.
If the function returns true then I want to change the value.
However if the function returns false then I do not want to change the value and keep the original selection value.
Currently it changes the value even when the statement returns false.
Any advice?
ASP Page
<asp:RadioButtonList ID="rblType" runat="server" AutoPostBack="True"
DataSourceID="SqlData" DataTextField="Type"
DataValueField="TypeID">
</asp:RadioButtonList>
VB file
Private selectionvalue As Integer
Protected Sub rblType_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles rblType.SelectedIndexChanged
Dim CheckListValidation As Boolean = CheckListBox()
If CheckListValidation = True Then
selectionvalue = rblType.SelectedItem.Value
Else
rblType.SelectedItem.Value = selectionvalue
End If
End Sub
Function CheckListBox() As Boolean
If lstbox.Items.Count <> "0" Then
If MsgBox("Are you sure you want to change option?", MsgBoxStyle.YesNo, " Change Type") = MsgBoxResult.Yes Then
Return True
Else
Return False
End If
Else
Return True
End If
End Function

The problem is when rblType_SelectedIndexChanged is executed, the selected item is already changed and the RadioButtonList doesn't "remember" the previously selected value. You need to keep the previously selected value between postbacks in order to achieve this.
I would suggest using ViewState. Create a property in code behind to represent the ViewState value:
Private Property PreviousSelectedValue() As String
Get
If (ViewState("PreviousSelectedValue") Is Nothing) Then
Return String.Empty
Else
Return ViewState("PreviousSelectedValue").ToString()
End If
End Get
Set(ByVal value As String)
ViewState("PreviousSelectedValue") = value
End Set
End Property
and in rblType_SelectedIndexChanged:
Protected Sub rblType_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rblType.SelectedIndexChanged
Dim CheckListValidation As Boolean = CheckListBox()
If CheckListValidation = True Then
'save the currently selected value to ViewState
Me.PreviousSelectedValue = rblType.SelectedValue
Else
'get the previously selected value from ViewState
'and change the selected radio button back to the previously selected value
If (Me.PreviousSelectedValue = String.Empty) Then
rblType.ClearSelection()
Else
rblType.SelectedValue = Me.PreviousSelectedValue
End If
End If
End Sub

Related

one dropdown gets correct value but the other dropdown reverts to default

I have two drop-down lists that get loaded and a default value from db - I do it in the Page Init event (did it in the page load too but changed to page init based on some research i did on this topic). then when I retrieve data from database for a particular item and setting a selected value of each drop down list, I see the correct value set in one of the drop downs but not the other. to be specific, ddlEcsrowService gets the correct value set from the BindListingDetails, while ddlListingType reverts back to the value set in BindListingTypesDdl. Any suggestions? thanks in advance. code is below:
======================
create.aspx
<asp:DropDownList ID="ddlEcsrowService" runat="server" Width="258px" EnableViewState="true" AutoPostBack="true" >
</asp:DropDownList>
<asp:DropDownList ID="ddlListingType" runat="server" Width="258px" EnableViewState="true" AutoPostBack="true" >
</asp:DropDownList>
====================
create.aspx.vb
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
If Not IsPostBack Then
BindEscrowServicesDdl()
BindListingTypesDdl()
If (Not Request("lstId") Is Nothing) Then
BindListingDetails(Request("lstId"))
End If
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Public Sub BindEscrowServicesDdl()
Dim tmpDt = CType(Application("EscrowServices"), DataTable)
ddlEcsrowService.DataTextField = "escrowservice"
ddlEcsrowService.DataValueField = "escrowserviceid"
ddlEcsrowService.DataSource = tmpDt
ddlEcsrowService.DataBind()
If tmpDt.Rows.Count Then
For index As Integer = 0 To tmpDt.Rows.Count - 1
If tmpDt(index)("escrowserviceid") = "2" Then
ddlEcsrowService.Items(index).Selected = True
Exit For
End If
Next
End If
End Sub
Public Sub BindListingTypesDdl()
Dim tmpDt = CType(Application("ListingTypes"), DataTable)
ddlListingType.DataTextField = "listingtype"
ddlListingType.DataValueField = "listingtypeid"
ddlListingType.DataSource = tmpDt
ddlListingType.DataBind()
If tmpDt.Rows.Count Then
For index As Integer = 0 To tmpDt.Rows.Count - 1
If tmpDt(index)("listingtypeid") = "1" Then
ddlListingType.Items(index).Selected = True
Exit For
End If
Next
End If
End Sub
Public Sub BindListingDetails(ByRef Id As String)
Try
Dim tmpdt As New DataTable()
Dim param As New List(Of SPParameter)
param.Add(New SPParameter("listingid", SqlDbType.BigInt, Request("lstId")))
tmpdt = SPs.ExecSPTableType("pgetownerlistingdetails", param)
If tmpdt.Rows.Count > 0 Then
ddlEcsrowService.SelectedValue = tmpdt(0)("escrowserviceid")
ddlListingType.SelectedValue = tmpdt(0)("listingtypeid")
End If
Catch ex As Exception
End Try
End Sub
I commented above - can you set a dropdownlist's selectedIndex like that?
In C# you have to do something like:
ListItem itemToSelect = ddl.Items.FindByValue(itemvalue);
if (!(itemtoSelect == null))
{
ddl.SelectedIndex = ddl.Items.IndexOf(itemToSelect);
}
You can replace the below pieces of code from your BindListingTypesDdl()
If tmpDt.Rows.Count Then
For index As Integer = 0 To tmpDt.Rows.Count - 1
If tmpDt(index)("listingtypeid") = "1" Then
ddlListingType.Items(index).Selected = True
Exit For
End If
Next
End If
with the one below. First check if the value you are looking for is present in the dropdownlist and keep the corresponding index of the item selected by default.
If ddl.Items.FindByValue("1") IsNot Nothing Then
ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue("1"))
End If
I found the solution. if I set the value using the code below, it works:
ddlListingType.ClearSelection()
For Each item1 In ddlListingType.Items
If item1.value = tmpdt(0)("listingtypeid") Then
item1.selected = True
End If
Next
thanks everyone for suggestions
UPDATE:
I figured out the reason for this working and for FindByValue not working: the reference data had this id column as char(2) but for the other drop-down that worked it was an int; so the database was returning "1 " and that is what was loaded into the drop-down. when listing details returned value it was in an int form and never matched the one inside the dropdown.

ASP.Net GridView.SelectRow(rowIndex as integer) method fails to pass rowIndex to SelectedIndexChanged event handler

In some ASP.Net code-behind, I call the SelectRow method of a custom grid control that inherits from System.Web.UI.WebControls.GridView.
Making the call:
If (ProgressGrid.Rows.Count > 0) Then
ProgressGrid.SelectRow(0)
End If
As expected, this generates a SelectedIndexChanged event, which is picked up by the handler:
Protected Sub ProgressGrid_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ProgressGrid.SelectedIndexChanged
Using db As New DataContext
Dim course = (From c In db.CourseResults
Where c.MemberID = MemberID AndAlso c.ResultID = CInt(ProgressGrid.SelectedDataKey.Value)
Select c).Single
' more code here
End Using
End Sub
My problem is that ProgressGrid.SelectedDataKey is nothing inside my event handler, causing a null-reference error. While debugging with Visual Studio 2010, I can see from the call stack that the ProgressGrid.SelectRow(0) was hit and that the ProgressGrid.Rows.Count is greater than zero. So why are all the "Selected..." properties on the ProgressGrid object set to nothing or -1? Any idea what I am doing wrong?
The custom Grid class contains this property which overrides the default GridView behavior:
Public Overrides Property SelectedIndex() As Integer
Get
If AutoPostback Or AllowSelect = False Then
Return MyBase.SelectedIndex
Else
If HttpContext.Current Is Nothing Then
Return Nothing
Exit Property 'Exit if in design mode
End If
Dim index As String = Page.Request(Me.ClientID + "_SelectedRow")
If (String.IsNullOrEmpty(index)) Then
If (ViewState("SelectedIndex") Is Nothing) Then
Return -1
Else
Return ViewState("SelectedIndex")
End If
Else
ViewState.Add("SelectedIndex", index)
Return CType(index, Integer)
End If
End If
End Get
Set(ByVal value As Integer)
MyBase.SelectedIndex = value
End Set
End Property
The debugger is unable to display the details for MyBase and the first calls to MyBase.SelectedIndex = value have the debugger's quick watch window return a null reference error. Once I reach the event handler, break points in the above property indicate that MyBase.SelectedIndex is nothing, despite attempting to set it to zero.
I discovered that setting the ViewState in the custom grid's SelectedIndex property fixed my problem. This allowed ViewState to hold the new index value and return it when the Get method was called on the property.
Set(ByVal value As Integer)
MyBase.SelectedIndex = value
ViewState("SelectedIndex") = value
End Set

VB.Net passing/calling a variable

How do I pass a value over to a module/function. Whenever I search here or Google I am getting code for C# rather than VB.net
I want to be able to click on a button and pass a value to a module and action it. Each button has a value 1,2,3,4 etc... and they pass back to make a panel visible=true/false.
i.e. I want to say the below but when I click btnShow1 I want to pass this as a value to a function and hide/show the panel I am talking about.
Current code
Protected Sub btnShowQ1_Click(sender As Object, e As System.EventArgs) Handles btnShowQ1.Click
If panel1.Visible = True Then
panel1.Visible = False
Else
panel1.Visible = True
End If
End Sub
Guess code
'Protected Sub btnShowQ1_Click(sender As Object, e As System.EventArgs) Handles btnShowQ1.Click
vpanel = btnShowQ1.value
Call fncPanel(vpanel as string) as string
End Sub
Then somewhere - I guess in App_code I create function.vb
Imports Microsoft.VisualBasic
Public Class ciFunctions
Public Function fncPanel(vPanel as string)as string
If (vPanel).visible = False then
(vPanel).visible = true
Else
(vPanel).visible = false
End IF
End Function
End Class
Set the button's CommandArgument property to the panel number to which it shows or hides:
<asp:Button ID="Button1" runat="server" Text="Show/Hide" CommandArgument="1" />
<asp:Button ID="Button2" runat="server" Text="Show/Hide" CommandArgument="2" />
On the button click event:
Private Sub Button_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click, ...
' get the button which triggers this event
Dim thisButton As Button = DirectCast(sender, Button)
' construct the panel name to toggle visibility from the button's CommandArgument property
Dim panelName as String = "panel" & thisButton.CommandArgument
' call the function, passing the panel name and the reference to current page
TogglePanel(Me, panelName)
End Sub
You can add all the buttons click event handler to this sub by adding them to the Handles... list as above. Therefore you don't have to create event handler for each buttons on the page. Just one to handle them all.
Create the function to toggle visibility:
Sub TogglePanel(pg As Page, panelName As String)
' get the panel control on the page
Dim panel As Panel = DirectCast(pg.FindControl(panelName), Panel)
' toggle its visibility
panel.Visible = Not panel.Visible
End Sub
The pg parameter is required if you put this function in a class other than the page it runs on or in a module. If the function sit in the same page class, then pg is not required.
You should be able to just add a parameter of type Panel to the sub, and in the btnShow event, pass the item.
Public Sub ChangePanelVis(panel as Panel)
If panel.Visible then
panel.Visible = True
Else
panel.Visible = True
End If
End Sub
Protected Sub btnShowQ1_Click(sender As Object, e As System.EventArgs) Handles btnShowQ1.Click
ChangePanelVis(panel1)
End Sub

Context.Item value is coming as null

On a page we have submit button, on clicking it we are getting error due to m_strPageDefinition has null value. Following is the code of it for more insight. Only sometimes and only in production we are getting value of m_strPageDefinition as null, which is causing problems. Does anyone has idea why m_strPageDefinition is coming null.
Private m_strPageDefinition As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
If (Not Context.Items("MyXmlString") = Nothing) And (Not Context.Items("mFormID") = Nothing) Then
MyXMLString = Context.Items("MyXmlString")
MyHiddenXMLString.Value = MyXMLString
End If
Else
m_strPageDefinition = MyHiddenXMLString.Value
End If
End Sub
Private Property MyXMLString()
Get
Return m_strPageDefinition
End Get
Set(ByVal value)
m_strPageDefinition = value
End Set
End Property
You should consider being more consistent how you address m_strPageDefinition. Why are you accessing is a private variable instead of always using the Property setter? e.g.
Private m_strPageDefinition As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
If (Not Context.Items("MyXmlString") = Nothing) And (Not Context.Items("mFormID") = Nothing) Then
MyXMLString = Context.Items("MyXmlString")
MyHiddenXMLString.Value = MyXMLString
Else
MyXMLString = MyHiddenXMLString.Value
End If
Else
MyXMLString = MyHiddenXMLString.Value
End If
End Sub
Private Property MyXMLString()
Get
Return m_strPageDefinition
End Get
Set(ByVal value)
m_strPageDefinition = value
End Set
End Property
I believe your issue is coming from the missing "Else" I have included here in the Not IsPostBack statement. Forgive me for VB.NET is not a language I code in, so the format/structure might be off a bit.
I think the problem is here:
m_strPageDefinition = MyHiddenXMLString.Value
and more specifically: MyHiddenXMLString.Value is probably null.
I couldn't figure out where you declared MyHiddenXMLString, but how about making it a hidden variable (input type="hidden" .. ) on the aspx side and setting it's value when the page loads the first time.
Then you know the value will always be there and easy to access.
hth

FinByValue not working within context of a UserControl DropDownList

I am pulling my hair out with this one.
I have an Employee dropdownlist usercontrol (uxEmployee) and I have exposed the SelectedValue method as a property(SelectedValue).
Within my page I am trying to either set the value based on my data or add the value to the list if it is not currently on there.
No matter what I do it is adding the Set value to the list. Even when the value is already on the list; it is still adding the value. Basically FindByValue is always returning "Nothing" no matter what I do. Any help would be appreciated.
Public Property SelectedValue() As String
Get
Return uxEmployee.SelectedValue
End Get
Set(ByVal value As String)
If Not uxEmployee.Items.FindByValue(value) Is Nothing Then
uxEmployee.SelectedValue = value
Else
uxEmployee.Items.Insert(0, New ListItem(value, value))
uxEmployee.AppendDataBoundItems = True
uxEmployee.DataBind()
End If
End Set
End Property
Public WriteOnly Property Department() As String
Set(ByVal value As String)
_department = value
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not (IsPostBack) Then
Dim emp As New Employee()
With uxEmployee
If _department <> String.Empty Then
.DataSource = emp.GetByDept(_department)
Else
.DataSource = emp.GetList()
End If
.DataTextField = "FullName"
.DataValueField = "UserName"
.DataBind()
End With
End If
End Sub
my calling page uses the following in page load.. uxSalesleadv is an instance of uxemployee
Dim objPrj As ServiceProject = New ServiceProject()
objPrj = objPrj.GetItem(prjID)
With objPrj
uxSalesLead.SelectedValue = .SalesLead
End With
The method performs an exact match and is case-sensitive and culture-insensitive. Have you checked that the values are identical in the debugger?
Try using FindByName(). If it works, then the values are not being set properly when you initially set the data source.
After much trial and error and debugging I have figured out the problem.
I was able to get the control to work correctly when i moved my data assignment from the page_load to the pre_render event. This was not ideal though.. I eventually found that the usercontrol was setting the value before the actual databinding was taking place.
I have now moved the logic out of my Set property and now added logic to my controls page_load databinding to check if the previous SET value is in the databind list. If it isnt then it adds the item. This will allow me to use the usercontrol throughout my apps without any additional page code and worrying about item not in list errors.

Resources