CheckBoxList.Selected keeps coming back with False value - asp.net

I have a CheckBoxList on my page that isn't behaving very well.
The idea is that once the submit button on the form is clicked, the app should clear the database table of all rows pertaining to the specific user and then re-insert new ones based on the user's CheckBoxList selections.
The problem is that regardless of whether or not any (or all) items in the CheckBoxList are selected, the app keeps getting Selected = False.
Here's my code:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
loadRegions()
End Sub
Private Sub loadRegions()
Dim db As New Database
Dim sql As String = "select * from regions"
Dim dr As MySqlDataReader = db.execDB(sql, "Text", Nothing, "DataReader", False)
If dr.HasRows Then
cblRegion.DataSource = dr
cblRegion.DataTextField = "regionname"
cblRegion.DataValueField = "regionid"
cblRegion.DataBind()
End If
dr.Close()
End Sub
Protected Sub btnRegister_Click(sender As Object, e As System.EventArgs) Handles btnRegister.Click
' ============================================================
' There's more code in here, but it's irrelevant to this paste
' ============================================================
Dim sql As String = "delete from userregions where userid = " & lblUserID.Text & ";"
For i As Integer = 0 To cblRegion.Items.Count - 1
If cblRegion.Items(i).Selected Then
sql &= "insert into userregions (userid, regionid)" & _
"values(" & UserID & ", " & cblRegion.Items(i).Value & ")"
db.execDB(sql, "Text", Nothing, "None", False)
End If
Next
End Sub
For the record
I'm aware of the potential for SQL Injection here. I'll be going over to using Parameters as soon as I have the loop working.
Thanks for your time.
Any help will be greatly appreciated.

You only need to call loadRegions on the initial load and not on postbacks:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
loadRegions()
End If
End Sub
Otherwise you'll lose changed values and events are not triggered.

Add this line of copde "If IsPostBack Then Return" in Page_Load method.
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If IsPostBack Then Return
loadRegions()
End Sub

In page loaded, write the following:
If Not IsPostBack
loadRegions()
End If

Related

asp.net how do i transfer listbox values generated from a query to anoter listbox without a NullReferenceException error?

What i'm trying to do is to generate data on a ListBox from a query and then i can select some values, press a button and move those values to another ListBox.
When i try to move the values from a ListBox by the selecting the values and pressing the button i get the following error message:
System.NullReferenceException: 'Object reference not set to an instance of an object.' i think this is because im making a reference to the value and i'm not creating an instance of the value (correct me if i am wrong)
To fix this i believe i might have to instantiate each query value in an array to add to the listbox.
If this is correct what is the correct way to implement that array?
How i populate the ListBox
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
FillSitesListbox()
End Sub
Private Sub FillSitesListbox()
Try
dt = SQL.ExecQuery("SELECT s.Str_ID, s.Nm, d.str_grp_id, (Cast(s.Str_ID As varchar) + ' - ' + s.Nm + ' [ ' + Cast(d.str_grp_id As varchar) + ' ]' ) as IDDesc
FROM Retail_Store s left outer join store_group d on ( s.str_id = d.str_id )
ORDER BY s.Str_ID")
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
SitesListBox.DataTextField = "IDDesc"
SitesListBox.DataSource = dt
SitesListBox.DataBind()
End Sub
How i move values between ListBoxes
Protected Sub FromSiteButton_Click(sender As Object, e As EventArgs) Handles FromSiteButton.Click
SitesListBox.Items.Add(StoresListBox.SelectedItem)
SitesListBox.Items.Remove(SitesListBox.SelectedItem)
End Sub
Protected Sub FromStoreButton_Click(sender As Object, e As EventArgs) Handles FromSTOREButton.Click
StoresListBox.Items.Add(SitesListBox.SelectedItem)
StoresListBox.Items.Remove(SitesListBox.SelectedItem)
End Sub
How i execute a query
Public Function ExecQuery(query As String) As DataTable
Dim DBDT = New DataTable
Using DBCon As New SqlConnection(ConStr),
DBCmd As New SqlCommand(query, DBCon)
Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
Params.Clear()
DBCon.Open()
DBDT.Load(DBCmd.ExecuteReader)
End Using
Return DBDT
End Function
'Add Params
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New SqlParameter(Name, Value)
Params.Add(NewParam)
End Sub
End Class
It seems that the code that moves the items is wrong.
In the first click (FromSiteButton_Click) you add the SelectedItem of the StoresListBox to the SiteListBox and then remove the SelectedItem from SitesListBox. I think you should add to the StoreListBox and remove from Sites selected item of that box. The same happens in the move FromStore
In any case, to avoid NRE you should always test if the reference variables that you are using are Nothing or not before using them
Protected Sub FromSiteButton_Click(sender As Object, e As EventArgs) Handles FromSiteButton.Click
If SitesListBox.SelectedItem IsNot Nothing Then
StoresListBox.Items.Add(SitesListBox.SelectedItem)
SitesListBox.Items.Remove(SitesListBox.SelectedItem)
End If
End Sub
Protected Sub FromStoreButton_Click(sender As Object, e As EventArgs) Handles FromSTOREButton.Click
If StoresListBox.SelectedItem IsNot Nothing Then
SitesListBox.Items.Add(StoresListBox.SelectedItem)
StoresListBox.Items.Remove(StoresListBox.SelectedItem)
End If
End Sub

How to match the answer in vb.net and asp.net?

I random the 3 question to display on asp.net page. I want to match the security question with correct answer in database. But after I enter the correct answer in textbox and click the "Next" button, the answer cannot match the current question displayed on screen. But if I click the "Next" button, the next question displayed is matched with answer I enter on textbox in previous question. I think this is because the answer is match the question and answer after refresh the page. Please help. Here is my code. thanks
vb.net code
Dim SecurityQuestion As New DBDataContext
Dim randomNumber As Integer
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim SecurityQuestion As New DBDataContext
Dim rowCount As Integer = (From t In SecurityQuestion.tblSecurityQuestions Select t).Count + 1
End Sub
Protected Sub btnNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNext.Click
ValidateAnswer()
End Sub
Private Sub LoadSecurityQuestion()
Dim SecurityQuestion As New DBDataContext
Dim mySecurityQuestion = (From c In SecurityQuestion.tblSecurityQuestions Where c.PkID = randomNumber Select c)
Dim rowCount As Integer = (From t In SecurityQuestion.tblSecurityQuestions Select t).Count + 1
randomNumber = New Random().Next(1, rowCount)
With gvQuestion
.DataSource = mySecurityQuestion
.DataBind()
End With
End Sub
Private Sub ValidateAnswer()
Dim SecurityQuestion As New DBDataContext
Dim validate = (From r In SecurityQuestion.tblRegistrations From s In SecurityQuestion.tblSecurityQuestions _
Where s.PkID = r.Q01 And r.A01 = txtSecurityAns.Text And r.UserID = ad And s.PkID = randomNumber _
Select r)
If validate.Count > 0 Then
Msg3.Text = "Correct Answer"
Else
Msg3.Text = "Invalid Answer"
End If
End Sub
At the time I posted this answer, it looked like a small bit of your code might have been missing. As an example, I couldn't see where you were actually calling the method LoadSecurityQuestion, but it sounds like you may be acidentally re-calling the method LoadSecurityQuestion even after validation succeeds.
I think you can fix this problem by wrapping your call to LoadSecurityQuestion with an "if" qualifier. As an example, lets suppose that you were calling LoadSecurityQuestion in your Load Event handler. If you did that, your new Load event handler might read something like this:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
...
If IsPostBack Then
' If you wrap all of your Me.LoadSecurityQuestion calls
' with "If" statements like this one, then it should keep
' the security question from changing when the user
' enters the correct answer
If Msg3.Text <> "Correct Answer" Then
Me.LoadSecurityQuestion()
End If
End If
...
End Sub

Why is this insert code inserting data twice on button clicks?

The following code inserts same data two time in database table, but I want it to insert only one item when button is clicked.
What is the problem in this code?
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
If RadUpload1.UploadedFiles.Count >= 0 Then
Dim file As UploadedFile = RadUpload1.UploadedFiles(0)
SqlDataSource1.InsertParameters("photo").DefaultValue = "./upload/" & file.GetName()
'SqlDataSource1.InsertParameters("name").DefaultValue = TextBox1.Text
SqlDataSource1.Insert()
ListView1.DataBind()
End If
'UpdateProgressContext()
End Sub
You must be using both OnClick="Button1_Click" in your markup and Handles Button1.Click in your procedure.
Try removing one of them.

User enters code into TextBox, code gets added to URL (using session)

I'm using ASP.net 4.0 VB :)
I am using a session variable to add a user entered code into the url of each page. I can get the code to show up at the end of the page's URL that my textbox is on, but what do I add to every page to make sure that the session stays at the end of every URL that person visits during their session? This is the code from the page that the user enters their user code.
Protected Sub IBTextBoxButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles IBTextBoxButton.Click
Session("IB") = IBTextBox.Text
Dim IB As String = Session("IB")
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ProductID.Value = Request.QueryString("id")
If Session("IB") Is Nothing Then
tab4.Visible = "False"
Else
tab4.Visible = "True"
End If
End Sub
This is what I have in the page load of one of the other pages. What else do I add to make sure that variable is added to the URL of that page?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim IB As String
IB = Session("IB")
End Sub
string url = Request.Url.ToString();
string newUrl = url + url.Contains("?") ? "&" : "?" + "ib=" + Server.UrlEncode(IBTextBox.Text);
Response.Redirect(newUrl);
return;
The approach I might use would be to create a base page class that all of your pages can inherit. The base page would then inherit the System.Web.UI.Page.
Within your base page class, create a property for IB and also handle the page load event.
In that event, check if the QueryString has the IB parameter in it. If it does, set the property to the value in the parameter.
Private _IB As String
Public Property IB() As String
Get
Return _IB
End Get
Set(ByVal value As String)
_IB = value
End Set
End Property
Public Function GetIB(ByVal url As String) As String
If Not(_IB = String.Empty) Then
If (url.Contains("?")) Then
Return "&IB=" & _IB
Else
Return url & "?IB=" & _IB
End If
Else
Return url
End If
End Function
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not (String.IsNullOrEmpty(Request.QueryString("IB"))) Then
_IB = Request.QueryString("IB")
End If
End Sub
Finally in your markup you would need to place something like the following at the end of all of your links:
next page
I threw this code into the Master Page to make sure that every page knows whether or not the Session is there. Thanks for all the help everyone!
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
If Session("IB") Is Nothing Then
IBText.Visible = True
IBTextBox.Visible = True
IBTextBoxButton.Visible = True
Else
IBText.Visible = False
IBTextBox.Visible = False
IBTextBoxButton.Visible = False
lblIB.Visible = True
lblIB.Text = "Welcome, " + Session("First_Name") + " " + Session("Last_Name")
End If
End Sub

form_load issue with updating details using session variables and textboxes

I'm trying to allow users to update their details after logging in on an asp site using vb. Textboxes are populated with user details using session variables in the form_load. The textboxes should be editable but for some reason are not registering the changes when the submit button is clicked.
There is a similar question with the same issue Database not updating after UPDATE SQL statement in ASP.net that was never answered.
Please can someone advise
Thanks in advance
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Txt_Fname.Text = Session("First_Name")
Txt_LName.Text = Session("Last_Name")
Txt_ContactNumber.Text = Session("Cell_Number")
Txt_Email.Text = Session("Email_Address")
End Sub
Protected Sub Cmd_Submit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Cmd_Submit.Click
Command.Connection = Connection
Command.CommandText = "UPDATE dbo.User_Account Set First_Name = #First_Name, Last_Name = #Last_Name, Cell_Number = #Cell_Number, Email_Address = #Email_Address where Overall_ID = #Overall_ID"
Command.Parameters.AddWithValue("#First_Name", Txt_Fname.Text)
Command.Parameters.AddWithValue("#Last_Name", Txt_LName.Text)
Command.Parameters.AddWithValue("#Cell_Number", Txt_ContactNumber.Text)
Command.Parameters.AddWithValue("#Email_Address", Txt_Email.Text)
Command.Parameters.AddWithValue("#Overall_ID", Session("ID"))
Connection.Open()
Command.ExecuteNonQuery()
Connection.Close()
Response.Redirect("MyAccount.aspx")
End Sub
Add if not page.ispostback before your code in page_load.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Not Page.IsPostBack) then
Txt_Fname.Text = Session("First_Name")
Txt_LName.Text = Session("Last_Name")
Txt_ContactNumber.Text = Session("Cell_Number")
Txt_Email.Text = Session("Email_Address")
End If
End Sub

Resources