ok i'm banging my head on my keyboard again. With help form here so far i did get my mysql query to read the one field i wanted. but my issue is this:
Concept. A table holds button data, like caption, and other stuff for latter on. Like what TAB the button will activate on a click. <-- the later is not important right now as once i figure out this part i'm asking about i can figure it out easily i'm sure. SO. i have 21 buttons. Each button needs a caption that is located in the database. What i'm trying to figure out is how to loop through the database to get the caption for botton 1, then button two, and so on. Right now it is loading the same caption for all 21 buttons. here is my code:
Private Sub frm_MainConsole_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'PosdbDataSet.button_cat' table. You can move, or remove it, as needed.
Me.Button_catTableAdapter.Fill(Me.PosdbDataSet.button_cat)
'Procedures
Me.Show()
' Variables
Dim query As String
Dim command As MySqlCommand
Dim reader As MySqlDataReader
Dim TargetButton As Button
Try
'For button 1 through 21
dbconn()
For i As Integer = 1 To 21 Step 1
query = "select btn_caption from button_cat"
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader()
reader.Read()
'btn_Cat1.Text = reader("btn_caption")
'Get the button from the controls container
TargetButton = Controls("btn_Cat" & i)
TargetButton.Text = reader("btn_caption")
reader.Close()
Next
conn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
I appreciate ANY HELP you can give me. i learn by seeing code and manipulating it to do what i need it to do.
I'm using visual studio 2015 community and MySQL for my database and writing in Visual Basic.
You are rerunning your query during every loop cycle.
Do something like this:
''For button 1 through 21
dbconn()
query = "select btn_caption from button_cat"
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader()
For i As Integer = 1 To 21 Step 1
reader.Read()
''btn_Cat1.Text = reader("btn_caption")
''Get the button from the controls container
TargetButton = Controls("btn_Cat" & i)
TargetButton.Text = reader("btn_caption")
Next
reader.Close()
conn.Close()
Keep in mind that this code is potentially problematic in that it assumes that there will always be 21 results returned from the database.
If you want to prevent problems if there are fewer than 21 records returned, you can do something like this:
''For button 1 through 21
dbconn()
query = "select btn_caption from button_cat"
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader()
For i As Integer = 1 To 21 Step 1
If Not reader.Read() Then
''We are out of records. Exit the loop.
Exit For
End If
''btn_Cat1.Text = reader("btn_caption")
''Get the button from the controls container
TargetButton = Controls("btn_Cat" & i)
TargetButton.Text = reader("btn_caption")
Next
reader.Close()
conn.Close()
You can also rewrite this as a while loop, but you would need to re-implement your i counter.
Related
I am practicing programming in visual basic
I have 2 forms in visual basic.
The first form has a command button that will show the input data from the 2nd form
The second form has a textbox where I need to input a data and save it.
The data that I input in the 2nd form stores it in MySQL
the 1st form has a command button named "Show my Grade" and if I click that I want to display the Form 2 and show me the grade. It does work however if I didn't input any grade and then I click the "show my grade" button it crashes I don't know the error. I tried using the code "if READER.HasRows Then:
but still it won't work
also tried if READER.Read then:
else MessageBox.Show("there is no grade input at the moment")
Please help.
This is my current code in the command button in form 1.
Me.Visible = False
Form2.Show()
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=localhost;userid=root;password=qwerty;database=ssg"
Dim COMMAND As New MySqlCommand
Dim READER As MySqlDataReader
MySqlConn.Open()
COMMAND.Connection = MySqlConn
COMMAND.CommandText = "select grade from gradetable"
READER = COMMAND.ExecuteReader
Form2.TextBox1.Text = READER("grade")
End Sub
It works as long as I input a grade first, however if I didn't input any grade it crashes.
If I click the "Show my grade" button in form 1 without inputting a grade in form 2 I would like to just display a message saying "You still have no grade at the moment"
Please help.
The Using statement with a matching End Using. This is in place of Dim. It ensures that your objects are properly closed and disposed of even if there is an error. This is especially important for connections which should be closed as soon as possible.
I used the constructor of the connection to pass in the connection string. Setting the property is fine. This just saves a line of code.
Same idea with the command constructor. It can take the command text and the connection. Saves a little typing.
You had the right idea; using .HasRows. You just needed to add the READER.Read to get to the first record as explained in comments by jmcilhinney.
Private Sub GetGrade()
Using MySqlConn As New
MySqlConnection("server=localhost; userid=root; password=qwerty; database=ssg")
Using COMMAND As New MySqlCommand("select grade from gradetable", MySqlConn)
MySqlConn.Open()
Using READER As MySqlDataReader = COMMAND.ExecuteReader
If READER.HasRows Then
READER.Read()
Form2.TextBox1.Text = READER("grade")
Else
MessageBox.Show("Sorry, no grade yet.")
End If
End Using
End Using
End Using
End Sub
I have a datagridview that gets data from the database, it's working fine but then when i close the form and open it again it wont clear the previous content. It will output the previous selection with the new selection made.
I have tried this codes:
compSpecs.modelDatagridview1.DataSource = Nothing
compSpecs.modelDatagridview1.Rows.Clear()
compSpecs.modelDatagridview1.Columns.Clear()
But it still wont clear. Maybe i'm not doing it right. Please help.
This is my code:
Private Sub load_model2()
conn = New MySqlConnection
conn.ConnectionString = "server=127.0.0.1; port=3306; username=root; password=p#ssw0rd; database= atos_db"
Dim sda As New MySqlDataAdapter
Dim bsource As New BindingSource
compSpecs.modelDatagridview2.DataSource = Nothing
compSpecs.modelDatagridview2.Rows.Clear()
compSpecs.modelDatagridview2.Columns.Clear()
Try
conn.Open()
Dim query As String
query = "select * from atos_db.itemdetails_tbl left join atos_db.brand_tbl on itemdetails_tbl.brand_id = brand_tbl.brand_id left join atos_db.item_tbl on brand_tbl.item_id=item_tbl.item_id where item='" & itemCombobox2.Text & "'"
comm = New MySqlCommand(query, conn)
sda.SelectCommand = comm
sda.Fill(dbDataset)
bsource.DataSource = dbDataset
compSpecs.modelDatagridview2.DataSource = bsource
sda.Update(dbDataset)
conn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
Firstly, that implies that you're using the same instance of the form each time. If you create a new instance of the form each time you want to display it then there can't be anything left over from last time.
If you don't want to do that though, there's no use unbinding the grid from the data source if you're only going to rebind it again. If the data is still in the data source then the grid will just display it again. If you want to get rid of the data then you need to clear the data source. The grid displays what's in the data source so clear the data source and the grid will be cleared too.
I am making a CMS portal for my company which will fetch records from SQL server using ASP.NET:
My problem is that when I fetch values it only shows the last one. But my need is that it should display one by one values with say 5-10 seconds gap in between here is my code:
Imports System
Imports System.Data.Sql
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Dim connectionString As String = "Data Source=soemserv;Initial Catalog=data;User Id=master; Password=hushotn;"
Dim conn As New SqlConnection(connectionString)
Public Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
conn.Open()
Dim comm As New SqlCommand("select Queue,[Timing(IST)],[Status at],TAT,[Staffing at] from DTD_LCD_Queue_Status", conn)
Dim reader As SqlDataReader = comm.ExecuteReader
While reader.Read()
lblQueueName.Text = reader("Queue").ToString.Trim
lblTimingIST.Text = reader("Timing(IST)").ToString.Trim
lblStatusAt.Text = reader("Status at").ToString.Trim
lblTAT.Text = reader("TAT").ToString.Trim
lblStaffingAt.Text = reader("Staffing at").ToString.Trim
End While
End Sub
End Class
How do I loop though each record I tried Do and Loop but its not working...
Thanks in advance!
EDIT
One Step Ahead with no LUCK!!!!
I have written this code but still getting the last row only
For I As Integer = 0 To 15
lblTemp.Text = I.ToString
Dim comm As New SqlCommand("select Queue,[Timing(IST)],[Status at],TAT,[Staffing at] from DTD_LCD_Queue_Status where SrNo='" + lblTemp.Text + "';", conn)
Dim reader As SqlDataReader = comm.ExecuteReader
While reader.Read()
lblQueueName.Text = reader("Queue").ToString.Trim
lblTimingIST.Text = reader("Timing(IST)").ToString.Trim
lblStatusAt.Text = reader("Status at").ToString.Trim
lblTAT.Text = reader("TAT").ToString.Trim
lblStaffingAt.Text = reader("Staffing at").ToString.Trim
Thread.Sleep(2000)
End While
Next
Note I have dynamically given rows i.e 0 to 15
Please guide me!!
Only the last values are printed because : you are fetching a group of rows(data) through the readr and in first iteration of the while loop the first rows(data) are copied to the controls then for the second iteration the contents in the controls are over written with the second row. This will happens in each iteration hence only the last data are displayed.
- This can be avoided by using
Group of controls which are dynamically created(but not practical and good)
using DataGridView(grid) to display the items How to do this
**The method you ware suggested (using Timer) is also possible but it is not a good programming practice only the last values ware displayed all the others flashed for a duration of 5-10 seconds **
So, for some reason I can't work out I think the below is only retrieving the 1st letter of the value within the column I'm trying to search. (Note: the database is called m1 and contains 11 columns in total).
I tested the query first in SQL Admin and it worked properly (I think).
I then wrote this myself using documentation, I think I've more that likely made a mistake somewhere..
Dim hostnameQuery As String = "SELECT `HOSTNAME` FROM `m1` WHERE 1"
Dim SQLConnection As New MySqlConnection(My.Settings.connStr)
Dim cmd As New MySqlCommand(hostnameQuery, SQLConnection)
Try
SQLConnection.Open()
cmd.ExecuteNonQuery()
Dim reader As MySqlDataReader
reader = cmd.ExecuteReader
While reader.Read
main.Label64.Text = (reader.GetChar(0))
End While
Catch ex As Exception
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
I added this to a button click so when I click the button only the letter 'M' appears but the value is 'M1'
What have I done wrong?
That's because you requested only a character. Try using GetString() instead of GetChar() :
main.Label64.Text = (reader.GetString(0))
There are many things that can be improved in your code.
First of all, you can remove the condition WHERE 1, because it means "EVERYTHING" so it is not useful.
Secondly, you can avoid calling cmd.ExecuteNonQuery() because it is usually used to run an instruction that does not return anything (like INSERT).
Finally, if you are interested only to the first returned row, you can avoid the While loop and use cmd.ExecuteScalar() instead.
To summarize, instead of:
cmd.ExecuteNonQuery()
Dim reader As MySqlDataReader
reader = cmd.ExecuteReader
While reader.Read
main.Label64.Text = (reader.GetChar(0))
End While
simply do this:
main.Label64.Text = Convert.ToString(cmd.ExecuteScalar())
im trying to retrieve some data using a reader in vb.net. I dont have any issue retrieving certain columns of the data for each row but i want to retrieve all data in each row. I've tried a couple of different things with the getstring() command but it isnt working and i cant seem to find any help googling the issue. my code is this
Private Function QueryDown(ByVal queryString)
Dim returnInfo As New StringBuilder
Try
Dim newQuery As String() = Split(queryString, ":")
For Each Query In newQuery
Dim cmd As New MySqlCommand(Query, connection1)
Dim reader As MySqlDataReader
reader = cmd.ExecuteReader()
While reader.Read()
For a = 0 To reader.FieldCount
Dim strng As String = reader.GetString(a)
returnInfo.Append(strng & ",")
Next
returnInfo.Append(";")
End While
reader.Close()
Next
Catch ex As Exception
console("Error with MySQL: " & ex.Message)
Return ex.Message
End Try
Return returnInfo.ToString
End Function
sorry the error i get when using this code is
There is already an open DataReader
associated with this Connection which
must be closed first
but if i change getstring(a) to getstring(1) everything is fine, im confused.
any help here would be great, i want to formatted code to come back column,column,coloumn;nextrow, as you can see (i hope). Because each of my table has a different amount of coloumns and i want to be able to use the same function for each one. thanks again.
Upper limit is reader.FieldCount - 1 not reader.FieldCount in:
For a = 0 To reader.FieldCount - 1
when a reaches reader.FieldCount there is an exception => reader.Close() is not executed => I suppose you call this function (or another) to open a new reader with the same connection => error.
When you call getstring(1) its working because 1 is within [0, FieldCount-1]
Update:
As #Zach Green said, try to always use using when ever possible which is a replacement for try...finally{ .Dispose() }: the dispose in finallyis applied to object beeing "used" and calling for DataReader/DataConnection it will call .Close() for you.