How to load the state of checkboxlist in database? - asp.net

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.

Related

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()

how to find the created textbox on a dynamic gridview in vb.net?

Hi I'm about to update some data through a textbox created on a dynamic filled Gridview but sadly when I click the update button, my code cannot read what I have inputed on those textboxes. Heres my code:
sqlcon = New SqlConnection(conString)
Dim id = GridAnswers.DataKeys(e.RowIndex).Value
Dim row As GridViewRow = TryCast(GridAnswers.Rows(e.RowIndex), GridViewRow)
Dim ChoiceDescription As TextBox = TryCast(row.FindControl("ChoiceDescription"), TextBox)
Dim Rating As TextBox = TryCast(row.FindControl("Rating"), TextBox)
DropDownList)
Using sqlcon As New SqlConnection
Dim sql As String = "UPDATE CS_RefQuestionChoice SET ChoiceDescription=#choice, RatingID=#ratingid WHERE ChoiceID=#qid"
Using cmd As New SqlCommand(sql, sqlcon)
cmd.Parameters.AddWithValue("#choice", ChoiceDescription.Text)
cmd.Parameters.AddWithValue("#ratingid", Rating.Text)
cmd.Parameters.AddWithValue("#id", id)
sqlcon.Open()
cmd.ExecuteNonQuery()
sqlcon.Close()
End Using
End Using
GridAnswers.EditIndex = -1
gridbind()
Check to bind the gridview only if the page is not posted back.

NullReferenceException - Object reference not set to an instance of an object

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.

How to retain edited Textbox value after submit?

My Scenario,
I reloaded ny page with previous data that was available for my login.Now i try to edit the textbox and update .It either updated or doesnt retain the edited value in Textbox.
objConn.Open()
Dim myControl As TextBox = FindControl("txtName")
Dim cmd As New SqlCommand("sp_UpdateNewmember", objConn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = Username
cmd.Parameters.Add(New SqlParameter("#FirstName", DirectCast(myControl, TextBox).Text))
cmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = txtlastname.Text
Anyone can help please.
When a page is requested very first time, you have to fetch a row from the table and assign values to the controls properties.
protect Sub Page_Load()
IF Not IsPostBack Then
//Retrieve a record
End If
End sum
To update a record, code should be like this:
Dim myControl As TextBox = FindControl("txtName")
Dim cmd As New SqlCommand("sp_UpdateNewmember", objConn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#UserName", SqlDbType.VarChar,30).Value = Username
cmd.Parameters.Add("#FirstName",SqlDbType.VarChar,30).Value= myControl.Text
cmd.Parameters.Add("#LastName", SqlDbType.VarChar,30).Value = txtlastname.Text
objConn.Open()
cmd.ExecuteNonQuery()
objConn.Close()
please write code inside this
if (!ispostback)
{
//code
}

VB.NET: How can I use ExecuteSQLCommand and return my data in a datatable and access it?

This is what I'm trying...
Dim myCommand as SqlCommand
Dim myTable as New xsdObject.ObjectDataTable
myCommand = DataAccess.GetSQLCommand( "MyStoredProc", _
CommandType.StoredProcedure, SourceServer.ConnectionLocal)
myCommand.Connection.ChangeDatabase("MyDatabase")
myCommand.Parameters.AddWithValue("#Parameter", DataValue)
ExecuteSQLCommand(myCommand, myTable)
'How to access my data ?
Here is an example without the datatable, as mentioned in your comment.
Dim reader As SqlDataReader= MyCommand.ExecuteReader
Dim MyList as new List(Of WhateverObject)
Do While reader.Read
Dim obj as new WhateverObj
obj.Property1 = Reader.GetInt32(0)
obj.Property2 = Reader.GetString(1)
MyList.add(obj)
Loop
reader.Close()
myCommand.Dispose()
For the sake of complete answer that matches the title, with a dataset:
Dim Adapter As New SqlDataAdapter(myCommand)
Dim ds As DataSet = New DataSet
Adapter.Fill(ds)
The Datatable:
Dim resultTable as DataTable = ds.Tables(0)
To put the results in a DataTable, you need to create a SqlDataAdapter around the SqlCommand and call its Fill method.

Resources