I've managed to put all items in a ListBox, also have the first character defined kto, how to insert only those values from List column into Listbox that begin with that character kto.
Just to mention that kto is value from 0 to 9, always a number.
Dim SqlSb As New SqlConnectionStringBuilder()
SqlSb.DataSource = ".\sqlexpress"
SqlSb.InitialCatalog = "Konta"
SqlSb.IntegratedSecurity = True
Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
SqlConn.Open()
Dim cmd As SqlCommand = SqlConn.CreateCommand()
cmd.CommandText = "SELECT List FROM Konta"
Dim kto = Left(Label1.Text, 1)
'Label3.Text = kto
Using reader As SqlDataReader = cmd.ExecuteReader
While (reader.Read())
Me.ListBox1.Items.Add(reader("LIST"))
End While
End Using
SqlConn.Close()
End Using
Try this
Dim SqlSb As New SqlConnectionStringBuilder()
SqlSb.DataSource = ".\sqlexpress"
SqlSb.InitialCatalog = "Konta"
SqlSb.IntegratedSecurity = True
Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
SqlConn.Open()
Dim cmd As SqlCommand = SqlConn.CreateCommand()
Dim kto = Left(Label1.Text, 1)
cmd.CommandText = "SELECT List FROM Konta WHERE List LIKE '" & kto.toString & "%'"
ListBox1.Items.Clear
Using reader As SqlDataReader = cmd.ExecuteReader
While (reader.Read())
Me.ListBox1.Items.Add(reader("LIST"))
End While
End Using
SqlConn.Close()
End Using
In your while loop, before adding the item in the listbox check the date type of reader("LIST") and add it only if matches the required type.
You can check the type using the following code:
reader.GetFieldType(0)
Related
Dim connect As String = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Using conn As New SqlConnection(connect)
Dim dt As DataTable = New DataTable()
Dim sql As String = "SELECT ID,Name,Class,Date FROM stuattrecordAMPM"
Using command As New SqlCommand(sql, conn)
Using adapter As New SqlDataAdapter(command)
Dim i As Integer = 0
For i = 0 To dt.Rows.Count - 1
Dim sy As String = dt.Rows(i).Item(0).ToString
Next
'command.Parameters.Add("#ID", SqlDbType.Int).Value = Convert.ToInt32(TextBox1.Text)
adapter.Fill(dt)
TextBox1.Text = dt(0)(0)
End Using
End Using
End Using
This code working properly asper my expectation. When I use "where ID=#ID" in sqlcommand It's showing error: 'Input string was not in a correct format.'
Dim connect As String = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Using conn As New SqlConnection(connect)
Dim dt As DataTable = New DataTable()
Dim sql As String = "SELECT ID,Name,Class,Date FROM stuattrecordAMPM where ID=#ID"
Using command As New SqlCommand(sql, conn)
Using adapter As New SqlDataAdapter(command)
Dim i As Integer = 0
For i = 0 To dt.Rows.Count - 1
Dim sy As String = dt.Rows(i).Item(0).ToString
Next
command.Parameters.Add("#ID", SqlDbType.Int).Value = Convert.ToInt32(TextBox1.Text)
adapter.Fill(dt)
TextBox1.Text = dt(0)(0)
End Using
End Using
End Using
In this code I'm getting error. Could someone help me how to declare "#ID". Thank you..
Please check the error description.
enter image description here
That's maybe because you are trying to add parameters using the statement of the adapter.
Try this:
Dim idValue As Int = Convert.ToInt32(TextBox1.Text)
Dim dt As DataTable = New DataTable()
Dim connect As String = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Using conn As New SqlConnection(connect)
Dim sql As String = "SELECT ID,Name,Class,Date FROM stuattrecordAMPM where ID=#ID"
Using command As New SqlCommand(sql, conn)
command.Parameters.Add("#ID", SqlDbType.Int).Value = idValue
Using adapter As New SqlDataAdapter(command)
adapter.Fill(dt)
End Using
End Using
End Using
Dim i As Integer = 0
For i = 0 To dt.Rows.Count - 1
Dim sy As String = dt.Rows(i).Item(0).ToString
Next
TextBox1.Text = dt(0)(0)
If you want to change the way you using to parse string to int:
Dim idValue As Int = Integer.Parse(TextBox1.Text)
Dim dt As DataTable = New DataTable()
Dim connect As String = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Using conn As New SqlConnection(connect)
Dim sql As String = "SELECT ID,Name,Class,Date FROM stuattrecordAMPM where ID=#ID"
Using command As New SqlCommand(sql, conn)
command.Parameters.AddWithValue("ID", idValue)
Using adapter As New SqlDataAdapter(command)
adapter.Fill(dt)
End Using
End Using
End Using
Dim i As Integer = 0
For i = 0 To dt.Rows.Count - 1
Dim sy As String = dt.Rows(i).Item(0).ToString
Next
TextBox1.Text = dt(0)(0)
it looks like in your broken code you need/want to have multiple "id" or more than one value. You can do this, but you ALSO then have to add the parameters to the source sql string.
You can't just add, or have multiple #ID values for the one "#ID".
If you want more than one ID value in the same sql query, then you have to add multiple "#id1" then "#id2" and so on to the sql text for this to work.
So, if you have ONE "#ID" then fine.
However, if you have say id 2, 134, 222?
Then you would have to add each parmater to the sql string.
You can do it this way:
dim strSQL as string = "SELECT * FROM MyTable"
dim strWhere as string = ""
dim cmdSQL as New Sqlcommand("", new Sqlconneciton("con string here")
' add first #id
strWhere = "#ID1"
cmd.SQL.Paramters.Add("#ID1", SqlDbType.Int).Value = 124
' add 2nd #!id
strWhere &= ",#ID2"
cmd.SQL.Paramaters.Add("#ID2", SqlDbType.Int).Value = 456
' and so on and so on
cmdSQL.CommandText = strSQL & " WHERE ID IN (" & strWhere & ")"
dim rstData as new DataTable()
cmdSQL.conneciton.Open()
rstData.Load(cmdSQL.ExectuteReader())
Note VERY interesting that you can create the sql command object, and are 100% free to add as many new parameters as possible to the cmdSQL object, and EVEN do so without having the sql command/text set for the sql command object.
However, you EVENTUALLY will have to setup/provide/have the sql shoved into that command object. So, build up the multiple "#id1, #id2" etc., and then shove that whole correct sql string into the cmdSQL object, and it will work.
However, as noted, you are 100% free to add as many parameters to the cmdSQL object, and even do so without having the SQL made/set/created for the cmdSQL object. They thus can be created 100% independent of the existing sql string/text (or better said lack of that sql string during the parameter adding process).
Well its been a while since my last post about saving loops through checkboxlist.So I did manage to check the input before it saved into table, but somehow it couldnt save any data even if wasnt duplicate one.
Wanted to create a function to check if each checkboxlist is already present within the table but I cant manage it because it needs value from this script so I skip it.
Using conn2 As New SqlConnection()
conn2.ConnectionString = ConfigurationManager _
.ConnectionStrings("BackboneConnectionString").ConnectionString()
Using cmd As New SqlCommand
cmd.CommandText = "Insert into EL_MstFunctionalNilai values(#IDFunc, #nik, #IDFuncParent, #IDFuncChild, #IDFuncMtr, '', '', '0')"
cmd.Connection = conn2
conn2.Open()
For Each item As ListItem In CheckBoxList2.Items
If item.Selected Then
'cmd.Parameters.Clear()
Dim urutan As Int32 = GetNumberFunctional()
Dim str As String = item.Value.ToString
Dim strArr() As String = str.Split("_")
Dim IDFunctionalParent1 As String = strArr(0)
Dim IDFunctionalChild1 As String = strArr(1)
Dim IDFunctionalMtr1 As String = strArr(2)
cmd.CommandText = "select count(*)as numrows from el_mstFunctionalnilai where nik = #nik and idfuncmtr = #IDFuncMtr"
cmd.Parameters.AddWithValue("#nik", txtnik.Text)
cmd.Parameters.AddWithValue("#IDFuncMtr", IDFunctionalMtr1)
queryresult = cmd.ExecuteScalar()
If queryresult = 0 Then
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("#IDFunc", urutan)
cmd.Parameters.AddWithValue("#nik", txtnik.Text)
cmd.Parameters.AddWithValue("#IDFuncMtr", IDFunctionalMtr1) 'mtr
cmd.Parameters.AddWithValue("#IDFuncParent", IDFunctionalParent1) 'parent
cmd.Parameters.AddWithValue("#IDFuncChild", IDFunctionalChild1) 'child
cmd.ExecuteNonQuery()
'Label1.Text = queryresult --> already check if queryresult has value
End If
End If
Next
conn2.Close()
End Using
End Using
When its executed no error tho, so I cant figure it out what Im missing. Well how do I fix this up?
Thanks.
el_mstFunctionalnilai
EL_MstFunctionalNilai
Which is it? Be careful about capitalization.
I have guessed at all the SqlDbType Please check your database to get the actual types.
Code following your pattern with 2 hits to database.
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim queryResult As Integer
'Pass the connection string directly to the constructor of the connection
Using conn2 As New SqlConnection(ConfigurationManager.ConnectionStrings("BackboneConnectionString").ConnectionString())
'Pass the command text and the connection directly to the command constructor
'You do not need as alias for Count
Using cmd As New SqlCommand("select count(*) from EL_MstFunctionalNilai where nik = #nik and idfuncmtr = #IDFuncMtr", conn2)
conn2.Open()
'This value does not appear to change in the loop so I moved it outside the loop
Dim urutan As Int32 = GetNumberFunctional()
'Add the parameters outside of the loop and only change the value inside the loop
'The value of the text box can't change inside the loop so it can be assigned outside the loop
cmd.Parameters.Add("#nick", SqlDbType.Int).Value = CInt(txtnik.Text)
cmd.Parameters.Add("#IDFuncMtr", SqlDbType.VarChar)
Using cmd2 As New SqlCommand("Insert into EL_MstFunctionalNilai values(#IDFunc, #nik, #IDFuncParent, #IDFuncChild, #IDFuncMtr, '', '', '0')", conn2)
cmd2.Parameters.Add("#IDFunc", SqlDbType.Int).Value = urutan
cmd2.Parameters.Add("#nik", SqlDbType.Int).Value = CInt(txtnik.Text)
cmd2.Parameters.Add("#IDFuncMtr", SqlDbType.VarChar) 'mtr
cmd2.Parameters.Add("#IDFuncParent", SqlDbType.VarChar) 'parent
cmd2.Parameters.Add("#IDFuncChild", SqlDbType.VarChar) 'child
For Each item As ListItem In CheckBoxList2.Items
If item.Selected Then
Dim str As String = item.Value.ToString
Dim strArr() As String = str.Split("_"c)
Dim IDFunctionalParent1 As String = strArr(0)
Dim IDFunctionalChild1 As String = strArr(1)
Dim IDFunctionalMtr1 As String = strArr(2)
cmd.Parameters("#IDFuncMtr").Value = IDFunctionalMtr1
queryResult = CInt(cmd.ExecuteScalar())
If queryResult = 0 Then
cmd2.Parameters("#IDFuncMtr").Value = IDFunctionalMtr1 'mtr
cmd2.Parameters("#IDFuncParent").Value = IDFunctionalParent1 'parent
cmd2.Parameters("#IDFuncChild").Value = IDFunctionalChild1 'child
cmd.ExecuteNonQuery()
End If
End If
Next
End Using
End Using
End Using
End Sub
I think it would be easier using one query that both checks for the existence of the record and inserts it if it doesn't exist.
Protected Sub Method2()
Dim urutan As Int32 = GetNumberFunctional()
Using cn As New SqlConnection(ConfigurationManager.ConnectionStrings("BackboneConnectionString").ConnectionString())
Using cmd As New SqlCommand("If Exists (Select 1 From EL_MstFunctionalNilai where nik = #nik and idfuncmtr = #IDFuncMtr) Select 0 Else Select 1 Insert into EL_MstFunctionalNilai values(#IDFunc, #nik, #IDFuncParent, #IDFuncChild, #IDFuncMtr, '', '', '0');", cn)
cmd.Parameters.Add("#nik", SqlDbType.Int).Value = CInt(txtnik.Text)
cmd.Parameters.Add("#IDFuncMtr", SqlDbType.VarChar)
cmd.Parameters.Add("#IDFunc", SqlDbType.VarChar).Value = urutan
cmd.Parameters.Add("#IDFuncParent", SqlDbType.VarChar)
cmd.Parameters.Add("#IDFuncChild", SqlDbType.VarChar)
cn.Open()
For Each item As ListItem In CheckBoxList2.Items
If item.Selected Then
Dim strArr() As String = item.Value.ToString.Split("_"c)
cmd.Parameters("#IDFuncMtr").Value = strArr(2)
cmd.Parameters("#IDFuncParent").Value = strArr(0)
cmd.Parameters("#IDFuncChild").Value = strArr(1)
cmd.ExecuteScalar()
End If
Next
End Using
End Using
End Sub
hi so i have this list that im currently using on a combobox that's why i have the idcategoria = 0 with the nomeCategoria = "Select your Category"so the combobox default item would be "select your category".
here is the code of the list
Public Shared Function ObterTodosC() As List(Of Ccategoria)
Dim lstTodos As List(Of Ccategoria) = New List(Of Ccategoria)
Dim p As Ccategoria = New Ccategoria()
p.IdCategoria = 0
p.NomeCategoria = "select your category"
lstTodos.Add(p)
Try
Using con As SqlConnection = New SqlConnection()
con.ConnectionString = myDAC._connectionString
Using cmd As SqlCommand = con.CreateCommand()
cmd.CommandText = "select * from Categoria"
con.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Dim p As Ccategoria = New Ccategoria()
p.IdCategoria = dr.GetInt32(0)
p.NomeCategoria = dr.GetString(1)
lstTodos.Add(p)
End While
End Using
End Using
Catch ex As SqlException
Throw ex
Catch ex As Exception
Throw ex
End Try
Return lstTodos
End Function
Now i want to use the same list on a datagridview and i wanted to know if there is a way to not show the id = 0 on the datagridview or do i have to create another list without the idCategorie = 0 for the datagridview, any ideas on this? thanks
Create another list from already loaded
Dim newList = lstTodos.Skip(1).ToList()
Skip method will return new collection without first item.
Notice that this approach will work only when - Select your Category - item is a first item in the list.
Or change your method to return list without - Select your Category - item and add it only when you need.
Public Shared Iterator Function ObterTodosC() As IEnumerable(Of Ccategoria)
Using con As SqlConnection = New SqlConnection()
con.ConnectionString = myDAC._connectionString
Using cmd As SqlCommand = con.CreateCommand()
cmd.CommandText = "select * from Categoria"
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Yield New Ccategoria With
{
.IdCategoria = reader.GetInt32(0),
.NomeCategoria = reader.GetString(1)
}
End While
End Using
End Using
End Function
Then you can create list of categories for datagridview
Dim forDataGridView = ObterTodosC().ToList()
Dim notSelectedCategory As New Ccategoria With
{
.IdCategoria = 0,
.NomeCategoria = "select your category"
}
Dim forComboBox = forDataGridView.ToList()
forComboBox.Insert(0, notSelectedCategory)
With this approach your remove side effect from ObterTodosC method.
So method responsibility will be only load items from database
How can I solve this problem? I do not want to use two connections.
ExecuteNonQuery only works if reader is closed.
oleCnn = New System.Data.OleDb.OleDbConnection
oleCnn.ConnectionString = ConnectionString
oleCmm = New OleDb.OleDbCommand()
oleCnn.Open()
oleStr = "SELECT ID_Process FROM MyProcessTable"
Dim reader As System.Data.OleDb.OleDbDataReader = oleCmm.ExecuteReader()
While reader.Read()
For i = 1 To NumExecutions
oleStr = "INSERT INTO MyOtherProcessTable(reader.getInt32(0))"
oleCmm.ExecuteNonQuery()
Next
End While
reader.Close()
oleCnn.Close()
Thank you
Use a list to store your IDs while reading the DataReader, then for each element of the list you should be able to execute your query with then same connection:
oleCnn = New System.Data.OleDb.OleDbConnection
oleCnn.ConnectionString = ConnectionString
oleCmm = New OleDb.OleDbCommand()
oleCnn.Open()
oleStr = "SELECT ID_Process FROM MyProcessTable"
Dim ids As New List(Of Integer)
Dim reader As System.Data.OleDb.OleDbDataReader = oleCmm.ExecuteReader()
While reader.Read()
ids.Add(reader.GetInt32(0))
End While
reader.Close()
For Each curr_id As Integer In ids
For i = 1 To NumExecutions
oleStr = "INSERT INTO MyOtherProcessTable(" & curr_id.ToString & ")"
oleCmm.ExecuteNonQuery()
Next
Next
oleCnn.Close()
P.S. I don't understand the For i = 1 To NumExecutions for loop, but I added it as you wrote it
I'm trying to get a single field back from the data. (I am searching by a primary key so I should get 0 or 1 answer). Please help. The table that I am querying has one entry with user = someone, input to several columns with the ans column having "a good answer"
Code:
Dim reader As SqlDataReader
Dim par As SqlParameter
Dim result As String
Dim sqlconn As SqlConnection
sqlconn = New SqlConnection("....")
sqlconn.Open()
Dim sqlcmd As SqlCommand
sqlcmd = New SqlCommand("Select Ans From Test Where User = #auser", sqlconn)
par = New SqlParameter
par.ParameterName = "auser"
par.Value = Textbox1.Text
sqlcmd.Parameters.Add(par)
reader = sqlcmd.ExecuteReader()
result = reader.GetString(0)
''//output to label
label1.Text = result
You need to read the data reader first to place it on the first row.
So instead of
reader = sqlcmd.ExecuteReader()
result = reader.GetString(0)
You'd insert the Read() method like so:
reader = sqlcmd.ExecuteReader()
if reader.Read() then '' <<<<< newly inserted code
result = reader.GetString(0)
end if
''// using statement will guarantee the object is closed and disposed
''// even if an exception occurs
Using sqlconn As New SqlConnection("...."), _
sqlcmd As New SqlCommand("Select Ans From Test Where User = #auser", sqlconn)
''// you can create, add, and set the value for a parameter all on one line
sqlcmd.Parameters.Add("#auser", SqlDbType.VarChar, 50).Value = Textbox1.Text
''//wait as long as possible to open the connection
sqlconn.Open()
''// if you're only getting the first column of the first row, use execute scalar
label1.Text = CString(sqlcmd.ExecuteScalar())
End Using