SQL Server result on textbox vb window form application - sql-server

I have a SELECT statement for ListView and for ListBox even for DataGrid the only problem is that I can't display a result to my TextBox I just want to use:
The MAX() Function
I want to used MAX() because it says that it will return the larges value of the selected column, since I used INCREMENT to my ID MAX() Function is my one way to do it.
I used this codes to generate the ID:
Dim p1num As Integer = 0
p1num += 1
txtPNumber.Text = p1num.ToString("D4")

I try to understand your question and I think you should used this:
Try:
Dim querystring As String = "SELECT MAX(pIDNo) FROM (Name of your Table)"
Using connection As New SqlConnection("Data Source=(local);Initial Catalog=(Name of your DB);Persist Security Info=True;User ID=(Your User);Password=(Your Pass)")
Dim command As New SqlCommand(querystring, connection)
connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader
Dim value = String.Empty
While reader.Read
value = reader.GetString(0)
End While
txtPNumber.Text = Today.Year.ToString().Substring(2, 2) & Today.Month.ToString().PadLeft(2, "0") & (Integer.Parse(value.Substring(4, value.Length - 4)) + 1).ToString("D4")
End Using
Catch ex As Exception
txtPNumber.Text = Today.Year.ToString().Substring(2, 2) & Today.Month.ToString().PadLeft(2, "0") & num.ToString("D4")
End Try
Try to make a Private Sub with it and used it to the Form Load if you want to display it after the program run or on button if you want a trigger to display the ID that you want.

Related

All Listview data show in textbox using loop

Dim Mysqlconn = New SqlConnection
Mysqlconn.ConnectionString = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Dim dt As DataTable = New DataTable("studentdata")
Mysqlconn.Open()
Dim query As String
query = "select ID from studentdata where Class='" & ComboBox1.Text & "'"
Dim Command = New SqlCommand(query, Mysqlconn)
Dim dr = Command.ExecuteReader(CommandBehavior.CloseConnection)
ListView1.Items.Clear()
Dim x As ListViewItem
Do While dr.Read = True
x = New ListViewItem(dr("ID").ToString)
ListView1.Items.Add(x)
Loop
For i = 0 To ListView1.Items.Count - 1
TextBox1.Text = ListView1.Items(i).SubItems(0).Text
Next
In this code, Textbox1 is showing the last row from Listview1. My requirement is all the Listview1 data show in textbox1 one after one from Listview1. Is this possible to show in textbox1 read all data from Listview1 using loop. Thank you...
A textbox only holds one string at a time. If it's set to allow multiline strings (not clear in the question) you can separate each item with a linebreak. Otherwise you can separate the strings using a delimiter like a comma.
Dim query As String = "select ID from studentdata where Class= #class"
Using conn As New SqlConnection("Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"), _
cmd As New SqlCommand(query, conn)
cmd.Parameters.Add("#class", SqlDbType.NVarChar, 20).Value = ComboBox1.Text
conn.Open()
Using dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
ListView1.Items.Add(New ListViewItems(dr("ID").ToString()))
End While
End Using
End Using
TextBox1.Text = String.Join(",", ListView1.Items.Select(Function(i) i.SubItems(0).Text))
Also note how I used a query parameter to include the combobox value in the SQL command. That's a big deal; anything else will give you trouble, usually sooner than later.
Using as loop, the proper way would be like so:
Dim lines As New List(Of String)
For i = 0 To ListView1.Items.Count - 1
lines.Add(ListView1.Items(i).Text)
Next
TextBox1.Lines = lines.ToArray()
You can't keep setting the Text property to a new value and expect the old value to hang around for no reason. You could append to the Text each time, but that is inefficient. The proper way is to create a list of the values, convert that to a String array and then assign that to the Lines property.
Note that there is no point getting the Text of the first subitem because that is the same as the Text of the item.

Pull value from SQL Server in VB.NET

I am attempting to pull values from an SQL Server table from VB.NET.
On VB Form 1, the number from NoTable, Row 1, is pulled successfully, and Label1 is updated with the value.
Dim command As SqlCommand
Dim query As String = "SELECT Number FROM NoTable"
command = New SqlCommand(query, con)
con.Open()
Dim datareader As SqlDataReader = cmd.ExecuteReader()
If datareader.Read() Then
Label1.Text = datareader.GetValue(0)
End If
datareader.Close()
On VB Form 2 I am attempting to pull the value from the second row, using:
Dim query As String = "SELECT Number FROM NoTable"
command = New SqlCommand(query, con)
con.Open()
Dim datareader As SqlDataReader = cmd.ExecuteReader()
If datareader.Read() Then
Label1.Text = datareader.GetValue(1)
End If
datareader.Close()
However, this does not work, and the label is not updated with the value from the second row.
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll
Additional information: Index was outside the bounds of the array."
How would I go about fixing this, so that on Form 2, the value from Row 2 is pulled, and so forth?
Thank you.
Firstly, you only get one column back from the reader, but you are indexing the columns with that 0 or 1. So you should always pass 0 to GetValue.
To index the row instead, try this. Assign a form number to each form (first line in my example) and use that to determine which record to assign to the Label. There is probably a more efficient way to do this (not returning all the records before it) but this solution should fit in your environment.
' in form # 1
Dim formNumber = 1
Dim command As SqlCommand
Dim query As String = "SELECT Number FROM NoTable"
command = New SqlCommand(query, con)
con.Open()
Dim datareader As SqlDataReader = cmd.ExecuteReader()
Dim index = 0
While index < formNumber
If datareader.Read() AndAlso index = formNumber Then
Label1.Text = datareader.GetValue(0)
End If
index += 1
End While
datareader.Close()
See https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getvalue(v=vs.110).aspx
And another similar question in c# Access a specific row in DataReader
Another way is to just return the row you need in the first place, without iterating over the records on the client side. Assuming there is another column with an index which is in the same order as the row you want to return, called "ID"
' in form # 1
Dim formNumber = 1
Dim command As SqlCommand
Dim query As String =
"SELECT Number FROM " & _
" (SELECT Number, Row_Number() OVER (ORDER BY ID) AS RowNumber " & _
" FROM NoTable) AS Results " & _
" WHERE Results.RowNumber = " & formNumber.ToString()
command = New SqlCommand(query, con)
con.Open()
Dim datareader As SqlDataReader = cmd.ExecuteReader()
Label1.Text = datareader.GetValue(0)
datareader.Close()
See https://msdn.microsoft.com/en-us/library/ms186734.aspx
GetValue(1) does not exist, as this would refer to a second column in the select statement. You are only asking for [Number] which would be datareader.GetValue(0)

VB.Net Ms Access Database. How can I display next value of a row to a lable one by one?

I'm looking for a way to set the next value of a row into a label
without using a Binding Navigator. ex: when I click the next button the next username in the username column should appear on the label and keep rolling the names.
Actually planing to make a quiz so I want to 'roll' the question.
What I've tried
I have bound data(ex: usernames) to a label using its property (Data Bindings). Now how can I display them in the label and with each button press have the next one appear?
OK, this is what did to achieve that on alternative way:
but this not working
I'm getting this error >> Syntax error in string in query expression 'tagno='2'. # line dr = Command.ExecuteReader
The objective is to on button click the count integer will increment and then the query will use count value to find question from database
for example if the increment value is 2 then the reader should return question from row where tagno two is.
the database table (quest) has following columns, Question Correct_Answer, tagno
Dim count As Integer
Private Sub btncontinue_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncontinue.Click
Dim conn As New OleDb.OleDbConnection
Dim olequery As New OleDb.OleDbCommand
Dim connString As String
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\" & Application.StartupPath & "\game.accdb"
conn.ConnectionString = connString
olequery.Connection = conn
count += 1
Dim dr As OleDbDataReader
'quest is the table name.
Dim query As String = "select question from quest where tagno='" & count & ""
cnnOLEDB.Open()
Dim command As New OleDbCommand(query, cnnOLEDB)
dr = Command.ExecuteReader
dr.Read()
lblquestion.Text = dr(0)
cnnOLEDB.Close()
End Sub

Compare values in DGV column with database values and add value to new DGV column

So, Access database has two columns 1st is seller name (SELLER) and second is it's code (CODE). Access database is database with all SELLER CODEs.
DGV is populated from other source and consists of some of CODEs from Access database.
DGV has one column with codes.
I would like to create and populate new column (SELLERNAME) in DGV with SELLER names based on DGV codes and Access database CODEs.
I am going to give an example since it's hard for me to explain this better :
DGV : Column 0, 1st value = 0055, in Access database code 0055 corresponds to the name John
so I would like to put name "John" in DGV Column1, 1st value, nest to "0055" and so on
Here is my code so far :
DataGridView1.Columns.Add("SELLERNAME", "SELLERNAME") '1
Dim cn As OleDb.OleDbConnection
Dim cmd As OleDb.OleDbCommand
Dim odr As OleDb.OleDbDataReader
Dim strSQL As String
cn = New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\SCodes.MDB")
strSQL = "SELECT SELLER, CODE FROM SCBASE"
cn.Open()
cmd = New OleDb.OleDbCommand(strSQL, cn)
odr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Do While odr.Read
For i As Integer = 0 To DataGridView1.Rows.Count - 1
DataGridView1.Rows(i).Cells(1).Value = odr.GetValue(1).ToString()
Next
Loop
I don't know what to do next after line For i As Integer = 0 To DataGridView1.Rows.Count - 1.
EDIT :
I think I am close but I need help with one line of code :
Using sqlconn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\SCodes.mdb")
Using sqlcmd = New OleDbCommand("Select SELLER, CODE From SCBASE Where CODE = #CODE ", sqlconn)
sqlcmd.Parameters.AddWithValue("#CODE ", DataGridView1.Rows(i).Cells(0).Value) 'HOW TO ADD THIS LINE IN LOOP BELOW
sqlconn.Open()
Dim result = sqlcmd.ExecuteReader()
Do While (result.Read())
For i As Integer = 0 To DataGridView1.Rows.Count - 1
DataGridView1.Rows(i).Cells(1).Value = (result("DOBAVLJAC"))
Next
Loop
End Using
End Using
I had no success with a trial and error. I am trying to put this line sqlcmd.Parameters.AddWithValue("#CODE ", DataGridView1.Rows(i).Cells(0).Value) in loop below but I am getting all sorts of error.
Yes, you are very close. You just need to .Add the Parameter outside the loop and then set its .Value inside the loop like this
Using sqlconn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\SCodes.mdb")
sqlconn.Open()
Using sqlcmd = New OleDbCommand("Select SELLER, CODE From SCBASE Where CODE = ?", sqlconn)
sqlcmd.Parameters.Add("?", OleDbType.VarWChar, 255)
sqlcmd.Prepare()
For i As Integer = 0 To DataGridView1.Rows.Count - 1
sqlcmd.Parameters(0).Value = DataGridView1.Rows(i).Cells(0).Value
Using result = sqlcmd.ExecuteReader()
If result.Read() Then
DataGridView1.Rows(i).Cells(1).Value = result("SELLER")
End If
End Using
Next
End Using
End Using

DataTimePicker for ListView

Is there a way to use DateTimePicker as your searching device for ListView?
I don't know how to use DateTimePicker as my search engine...
HERE IS THE CODES FOR MY SEARCH:
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim da As SqlDataAdapter
Dim ds As DataSet
Dim itemcoll(100) As String
Me.ListView1.View = View.Details
Me.ListView1.GridLines = True
ListView1.Items.Clear()
conn = New SqlConnection("Data Source=#####;Initial Catalog=#####;Persist Security Info=True;User ID=#####;Password=#####")
Dim strQ As String = String.Empty
strQ = "SELECT ControlNo,EmpNo,CheckOutDate,CheckOutTime,TaxiNo,PlateNo,Model,Make FROM dbo.ChkInOut WHERE ControlNo ='" + txtsearch.Text + "'"
cmd = New SqlCommand(strQ, conn)
da = New SqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcoll(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcoll)
Me.ListView1.Items.Add(lvi)
Next
There are few problems with your code as is, so let's take them one at a time
SqlCommand inherits from DbCommand, which implements the IDisposable interface.
The primary use of this interface is to release unmanaged resources.
The best way do that is with the Using keyword. For a code example of that, take a look at the sample code at the bottom of this page.
Same goes for SqlConnection, wrap it in a Using statement.
Don't concatenate strings together to make SQL queries, this opens your application up to SQL Injection attacks. There are examples of how to create parameterized queries here and here (unfortunately I didn't see a good example on MSDN).
In your case, the query will look like this:
strQ = "SELECT ControlNo, ..<rest of columns>.. ,Model,Make " & _
"FROM dbo.ChkInOut " & _
"WHERE ControlNo = #controlNo"
cmd = New SqlCommand(strQ, conn)
cmd.Parameters.AddWidthValue("#controlNo", txtsearch.Text);
... rest of code here ...
To query by a user specified date, you need to first get the date from the DateTimePicker.Value property. Then construct a query (like in the example above) and pass a parameter with the selected date. You may find this question abou SQL Server dates helpful.

Resources