NullReferenceException - Object reference not set to an instance of an object - asp.net

I am trying to run this code below. It was working previously, but when I added a second datareader, it stopped. Can anyone tell me what's wrong ?
Protected Sub btnSearchUser_Click(sender As Object, e As EventArgs) Handles btnSearchUser.Click
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim searchComm As String = "SELECT * FROM users WHERE username LIKE #username"
Dim user_id_select As New Integer
Dim searchSQL As New SqlCommand
conn.Open()
searchSQL = New SqlCommand(searchComm, conn)
searchSQL.Parameters.AddWithValue("#username", txtUserSearch.Text)
Dim datareader As SqlDataReader = searchSQL.ExecuteReader()
While datareader.Read
lstUsers.Items.Add(datareader.Item("username"))
End While
datareader.Close()
conn.Close()
Dim conn2 As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim selectComm As String = "SELECT user_id FROM users WHERE username=#username_selected"
Dim selectSQL As New SqlCommand
conn2.Open()
selectSQL = New SqlCommand(selectComm, conn2)
selectSQL.Parameters.AddWithValue("#username_selected", lstUsers.SelectedItem.Text.Trim)
Dim datareader2 As SqlDataReader = selectSQL.ExecuteReader()
While datareader2.Read
If datareader2.HasRows Then
user_id_select = datareader2("user_id")
lblUserSelected.Text = "Selected: " + lstUsers.SelectedItem.Text
ElseIf datareader2.HasRows = False Then
lblInvalidUsername.Visible = True
datareader2.Close()
End If
End While
conn2.Close()
End Sub
Hi,
I'm gettin a NullReference exception on lblUserSelected.Text = "Selected: " + lstUsers.SelectedItem.Text whenever I enter a username in txtUserSearch and click search, it was working previously.. I don't know what happened..
Can anyone tell me whats wrong?

I assume you're getting the NullReferenceException on this line:
selectSQL.Parameters.AddWithValue("#username_selected", lstUsers.SelectedItem.Text.Trim)
since you haven't specified the SelectedItem of the recently filled ListBox. To select the first item you could use this code:
While datareader.Read
lstUsers.Items.Add(datareader.Item("username"))
End While
If lstUsers.Items.Count <> 0 Then lstUsers.SelectedIndex = 0
You are also not handling the case that there are no usernames in the database, then the ListBox is empty and has no selected-item.

Related

Asp.net multible table access vb.net

and good day..
I have a code of asp.net in vb.net and work fine for one table but i need to add multible table of( master and dr ) to code the data is the sum from the two table but its different. can anyone help me..thanks advance for all
Private Sub getData(ByVal user As String)
Dim dt As New DataTable()
Dim connectionString As String
Dim connection As OleDbConnection
connectionString = ConfigurationManager.ConnectionStrings("Data_For_netConnectionString").ToString
connection = New OleDbConnection(connectionString)
connection.Open()
Dim sqlCmd As New OleDbCommand("SELECT * from master WHERE UserID = #user", connection)
sqlCmd.CommandText = _
"SELECT name, manistry, university, send, card FROM master "
Dim sqlDa As New OleDbDataAdapter(sqlCmd)
sqlCmd.Parameters.AddWithValue("#user", user)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
TextBox1.Text = dt.Rows(0)("manistry").ToString
TextBox2.Text = dt.Rows(0)("university").ToString
TextBox4.Text = dt.Rows(0)("send").ToString
TextBox21.Text = dt.Rows(0)("card").ToString
name.Text = dt.Rows(0)("name").ToString
End If
connection.Close()
End Sub

How to load the state of checkboxlist in database?

I got 1 checkboxlist with 6 checkboxes inside it (below is my database)
id : int
interest : bit
When I click one checkbox, the value is saved to my database as TRUE. Here is my code:
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim insertSql As String = "INSERT INTO tbinterest(interest) VALUES(#interest)"
Using myConnection As New SqlConnection(connectionString)
myConnection.Open()
Dim myCommand As New SqlCommand(insertSql, myConnection)
myCommand.Parameters.AddWithValue("#interest", SqlDbType.Bit).Value = 1
myCommand.ExecuteNonQuery()
myConnection.Close()
End Using
But somehow, when I load the page, it does not show the checked state (checked/unchecked). Here is my code in page load. Can you help me out? Thanks.
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Using myConnection As New SqlConnection(connectionString)
Dim objCmd_team As SqlCommand = New SqlCommand("SELECT [interest] FROM [tbinterest]", myConnection)
myConnection.Open()
Dim objReader As SqlDataReader = objCmd_team.ExecuteReader()
While (objReader.Read())
Dim currentCheckBox As ListItem = chkApprovers.Items.FindByText(objReader("interest"))
If currentCheckBox IsNot Nothing Then
currentCheckBox.Selected = True
End If
End While
End Using
your code seems to be correct.. please check this line with break point that listitem has value or not.
Dim
currentCheckBox As
ListItem =
chkApprovers.Items.
FindByText(objReader
("interest"))
If listitem is nothing then try this
Dim
currentCheckBox As
ListItem =
chkApprovers.Items.
FindByText(objReader.Item
("interest").ToString)
And one more thing, you are saving only bit value as interest then how did you match this with your checkbox.
you can match only with checkboy text value or id value
Hope this help.

Textbox.text does not show updated text in code

When I use the code below for some reason when Update is clicked, hospitaltextbox.text does not show the current value in the textbox? Just the value that was originally selected. Any idea why it is not reading what is currently in the textbox?
Dim reader As SqlDataReader = cmd.ExecuteReader()
If (reader.Read()) Then
HospitalTextBox.Text = reader(7)
FirstNameTextBox.Text = reader(9)
Session("ID") = reader(0)
End If
Protected Sub cmdUpdate_Click(sender As Object, e As EventArgs) Handles cmdUpdate.Click
Dim Test As String
Test = FirstNameTextBox.Text
Try
Dim Con As SqlConnection
Dim cmd As SqlCommand
Con = New SqlConnection
Con.ConnectionString = ""
Con.Open()
cmd = New SqlCommand
cmd.Connection = Con
cmd.CommandText = "UPDATE tbltest SET [Teaching Hospital Name] = #TeachingHospitalName, [Physician First Name] = #FirstName WHERE ID = #ID"
cmd.Parameters.Add(New SqlParameter("#ID", (Session("ID"))))
cmd.Parameters.Add(New SqlParameter("#TeachingHospitalName", HospitalTextBox.Text)) 'does not show text that was changed in the textbox?
cmd.Parameters.Add(New SqlParameter("#FirstName", Test))
cmd.ExecuteNonQuery()
Con.Close()
Catch ex As Exception
End Try
End Sub
Check your Page_Load function.
Are you doing something on PostBack to set the textbox value to something else?
If you're binding data, make sure it's done when Not IsPostback
If Not IsPostBack
BindData()

Session ASP.NET doesnt seem to work

I have the following code on my default.aspx
Label1.Text = Session("valueName").ToString()
And the following code on my login.aspx
Dim strCon As String = ConfigurationManager.ConnectionStrings("Goed").ConnectionString
'Create Connection String And SQL Statement
Dim strSelect As String = "SELECT COUNT(*) FROM tbl_LogIn WHERE Gebruiker = #Gebruiker AND Wachtwoord = #Wachtwoord"
Dim con As New SqlConnection(strCon)
Dim cmd As New SqlCommand()
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = strSelect
Dim Gebruiker As New SqlParameter("#Gebruiker", _
SqlDbType.VarChar)
Gebruiker.Value = TxtUs.Text.Trim().ToString()
cmd.Parameters.Add(Gebruiker)
Dim Wachtwoord As New SqlParameter("#Wachtwoord", _
SqlDbType.VarChar)
Wachtwoord.Value = TxtPw.Text.Trim().ToString()
cmd.Parameters.Add(Wachtwoord)
con.Open()
Dim result As Integer = DirectCast(cmd.ExecuteScalar(), Int32)
con.Close()
If result >= 1 Then
Response.Redirect("default.aspx")
Session("valueName") = TxtUs.Text.ToString()
Else
lblMsg.Text = "Gebruikers naam en of wachtwoord kloppen niet"
End If
End Sub
But it doesnt seem to help. I don't get any error or whatso ever, any idea?
The Redirect method ends the execution, so you have to set the session variable before redirecting:
Session("valueName") = TxtUs.Text.ToString()
Response.Redirect("default.aspx")
you are redirecting before setting the session. you should first set the session and then redirect the page.
Or
Your result variable is not 1 or bigger than 1. you should check that too

asp.net storing images

It's me your junior programmer extraodinaire
I'm trying to display an image from my database but when I try to extract the file it only contains 6 bytes of data which causes my program to throw an error. My instructor informed me that the file is too small for an image, leading me to believe that I'm not storing it properly. I would be most gracious if someone could identify any code that might cause this to happen.
this is my function grabbing/storing the file
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Dim _image As Byte()
_image = FileUpload1.FileBytes
Dim conn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
cmd.Connection = conn
cmd.CommandText = "Insert INTO mrg_Image(Image, UserId) VALUES('#image', #id)"
cmd.Parameters.AddWithValue("#image", FileUpload1.FileBytes)
cmd.Parameters.AddWithValue("#id", 4)
conn.Open()
dr = cmd.ExecuteReader
conn.Close()
'FileUpload1.SaveAs()
End Sub
conn.Open()
file_bytes is the variable that contains 6 bytes as oppose to a thousand+ which an image should have
Dim file_bytes As Byte() = cmd.ExecuteScalar()
Dim file_bytes_memory_stream As New System.IO.MemoryStream(file_bytes)
Dim file_bytes_stream As System.IO.Stream = DirectCast(file_bytes_memory_stream, System.IO.Stream)
Dim the_image As New System.Drawing.Bitmap(file_bytes_stream)
context.Response.ContentType = "image/jpg"
the_image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
conn.Close()
End Sub
Try replacing '#image' with #image.
Also replace ExecuteReader with ExecuteNonQuery.
I wasn't aware of the FileBytes property, I've always done it so...
Dim _image(FileUpload1.PostedFile.InputStream.Length) As Byte
FileUpload1.PostedFile.InputStream.Read(_image, 0, _image.Length)
Try this
cmd.CommandText = "Insert INTO mrg_Image(Image, UserId) VALUES(#image, #id)"
cmd.Parameters.Add("#image", SqlDbType.Image)
cmd.Parameters("#image") = FileUpload1.FileBytes
cmd.Parameters.AddWithValue("#id", 4)
Edit
Removed ";" forgot this was vb
Edit2
Changed [] to (). again forgot my VB

Resources