How to select one name in between dates form mysql database - mysql

I will explain this as much as possible.
I have a project which need to show the names from database to textboxes. I have 2 datetimepicker for searching between dates and 5 textboxes to show the names in mysql database. for example I select the from start date 2018/12/07 and end date 2019/01/07 in the datagridview it will show all the rows and columns in-between dates. However, I need the names to show on my 5 textboxes. I don't have a code since I don't know where to begin with.
In mysqldatabase I have only id,name,dateofentry.
In my form :
datetimepicker1 = startdate
datetimepicker2 = enddate
button1 = generatebutton
textbox1 = nametxt1
textbox2 = nametxt2
textbox3 = nametxt3
textbox4 = nametxt4
textbox5 = nametxt5
Update when I use this:
mysqlconn.Open()
COMMAND.Connection = mysqlconn
COMMAND.CommandText = "Select name from table1 where dateofentry between '" & Format(Me.startdate.Value, "yyyy-MM-dd") & "' AND '" & Format(Me.endtime.Value, "yyyy-MM-dd") & "'"
Dim sqlresult1 As Object
sqlresult1 = COMMAND.ExecuteScalar
Dim str1 As String
str1 = sqlresult1
nametxt1.Text = str1
mysqlconn.Close()
The same name shows in each of my 5 textboxes
Thank you for answering this question.

Explanations and comments in-line.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'The Using block ensures that your database objects are closed and disposed
'even if there is an error
Dim dt As New DataTable
Using cn As New MySqlConnection("Your connection string")
'Pass the Select statement and the connection to the constructor of the command
Using cmd As New MySqlCommand("Select name from table1 where dateofentry between #Date1 AND #Date2;", cn)
'Use parameters
cmd.Parameters.Add("#Date1", MySqlDbType.Date).Value = DateTimePicker1.Value
cmd.Parameters.Add("#Date2", MySqlDbType.Date).Value = DateTimePicker2.Value
'open the connection at the last possible moment
cn.Open()
'Execute scalar only returns the first row, first column of the result set
dt.Load(cmd.ExecuteReader)
End Using
End Using
'Then a little link magic to dump the first column of the table
'to an array
Dim names() = (From row In dt.AsEnumerable()
Select row(0)).ToArray
'If there are less than 5 records returned this
'code will fail, Add a check for this and
'adjest your code accordingly
TextBox1.Text = names(0).ToString
TextBox2.Text = names(1).ToString
TextBox3.Text = names(2).ToString
TextBox4.Text = names(3).ToString
TextBox5.Text = names(4).ToString
End Sub

SELECT *
FROM `tblPerson`
WHERE (date_field BETWEEN '2018-12-30 14:15:55' AND '2019-01-06 10:15:55')
LIMIT 5;
text1.text = dt.Rows[0]["name"].ToString();
text2.text = dt.Rows[1]["name"].ToString();
text3.text = dt.Rows[2]["name"].ToString();
text4.text = dt.Rows[3]["name"].ToString();
text5.text = dt.Rows[4]["name"].ToString();

Related

VB.Net - Combobox Not Showing the Data

Combobox2.text not showing the called data from the table. Any help will be appreciated!
Public Sub loadproductdata()
Dim i As Integer
str = "SELECT * FROM tbl_products INNER JOIN tbl_suppliers ON tbl_products.prod_supplier = tbl_suppliers.supp_ID WHERE prod_ID = '" & frm_ProductList.DataGridView1.SelectedRows(i).Cells(0).Value & "'"
cmd = New MySqlCommand(str, con)
con.Open()
dr = cmd.ExecuteReader()
If dr.Read() Then
TextBox1.Text = (dr.Item("prod_code").ToString())
TextBox2.Text = (dr.Item("prod_name").ToString())
ComboBox1.Text = (dr.Item("prod_category").ToString())
Label1.Text = (dr.Item("prod_supplier").ToString())
ComboBox2.Text = (dr.Item("supp_name").ToString())
TextBox3.Text = (dr.Item("prod_purchaseprice").ToString())
TextBox4.Text = (dr.Item("prod_retailprice").ToString())
TextBox5.Text = (dr.Item("prod_discount").ToString())
ComboBox3.Text = (dr.Item("prod_unit").ToString())
TextBox6.Text = (dr.Item("prod_stockqty").ToString())
TextBox7.Text = (dr.Item("prod_reorderlvl").ToString())
TextBox8.Text = (dr.Item("prod_description").ToString())
TextBox9.Text = (dr.Item("prod_remarks").ToString())
End If
con.Close()
End Sub
When a combo box is in DropDownList mode, as yours appears to be, to set its current value to an item from its list you should set the SelectedValue property. You should also consider filling the control with some kind of object that can maintain the difference between a key and a value items, to support a different display value versus backing value (supplier "Microsoft" has ID "6")
While dr.Read()
Dim kvp = new KeyValuePair(Of Integer, String) (0,"")
kvp.Value= (dr.Item("supp_name").ToString())
kvp.Key = DirectCast(dr.Item("supp_id"), Integer)
ComboBox2.Items.Add(kvp)
Loop
Combobox2.DisplayMember = "Value"
Combobox2.ValueMember = "Key"
Now, if you set SelectedValue = 6 in your other query the combo shows "Microsoft"
ps; it's actually a lot easier if you just use a datatable for this:
Dim dt = new DataTable
Dim da as MySqlDataAdapter("SELECT * FROM...", "conn string here")
da.Fill(dt)
'rename your combobox2 to supplierComboBox
supplierComboBox.DataSource = dt
supplierComboBox.DisplayMember = "supp_name"
supplierComboBox.ValueMember = "supp_id"
And it gets easier still if you use strongly typed datasets everywhere instead of this intensely manual yanking data around - but that's out of scope of this question

Save Datagridview if it is Checked by CheckboxColumn

Hello Everyone Good Afternoon,
I have an Object in a form and they are Datagridview1 and a Save Button the Datagridview1 will populate data from my Database on Form_Load and the Data will show with a Corresponding Checkbox. Like the Image below
and If you here is the code for that
Private Sub loadtech()
Dim con1 As MySqlConnection = New MySqlConnection("datasource=localhost;database=operations;userid=root;password=admin1950;Convert Zero Datetime=True")
Dim sql1 As MySqlCommand = New MySqlCommand("select TechName from technicians order by Category ASC", con1)
Dim ds1 As DataSet = New DataSet
Dim adapter1 As MySqlDataAdapter = New MySqlDataAdapter
con1.Open()
adapter1.SelectCommand = sql1
adapter1.Fill(ds1, "MyTable")
DataGridView1.DataSource = ds1.Tables(0)
con1.Close()
With DataGridView1
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "Technician / Electrician"
End With
DataGridView1.Columns.Item(0).Width = 150
DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
Me.DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True
Me.DataGridView1.Columns(0).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
Dim checkBoxColumn As New DataGridViewCheckBoxColumn()
checkBoxColumn.HeaderText = "Tag"
checkBoxColumn.Width = 30
checkBoxColumn.Name = "checkBoxColumn"
DataGridView1.Columns.Insert(0, checkBoxColumn)
End Sub
and my Question is how can I save the Checked Row in Database? Lets say I checked all of it so the Rows will be saved in Database. (Regardless of How many I Checked)
Here is my code but its not working. :(
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conn As MySqlConnection = New MySqlConnection("datasource=localhost;database=operations;userid=root;password=admin1950;Convert Zero Datetime=True")
conn.Open()
Dim comm As MySqlCommand = New MySqlCommand()
comm.Connection = conn
Dim name As String
For i As Integer = 0 To Me.DataGridView1.Rows.Count
name = Me.DataGridView1.Rows(0).Cells(1).Value
comm.CommandText = "insert into assignments(ElecAssigned) values('" & name & "')"
comm.ExecuteNonQuery()
Next
conn.Close()
End Sub
TYSM For future help
Yes, your loop is slightly incorrect. Try using this loop and see if that fixes your issue. The issue, you didn't use the i variable. It should be placed in Row(i) and you were looping from 0 to Count when it should be 0 to Count - 1
Dim name As String
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1 Step 1
If Me.DataGridView1.Rows(i).Cells(0).Value = True Then
name = Me.DataGridView1.Rows(i).Cells(1).Value
comm.CommandText = "insert into assignments(ElecAssigned) values('" & name & "')"
comm.ExecuteNonQuery()
End If
Next

Filtering MySql database with multiple checkboxes in VB.NET

I want to filter my datas which are stored in MySql database with combining multiple checkbox and textbox queries. You can find the screenshot of the form here:
SEARCH FORM:
TABLES:
PROJECTS TABLE
DETAILS TABLE
PS: Only ID field in Projects table is unique!
If user writes in any of these three textboxes than the rest of the textbox will getting empty. Currently it works fin with textboxes. I want to combine the seach criteria with the checkboxes.
Assume that user writes in TEXTBOX1 and selects FAS, VAPA and ACC from checkboxes than the result should be listed in my listview box.
Here's the codes I've come so far :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" And TextBox2.Text = "" And TextBox3.Text = "" Then
MsgBox("Bir arama kriteri girin!", MsgBoxStyle.Critical, "UYARI!")
Exit Sub
End If
ListView1.Items.Clear()
If TextBox1.Text <> "" Then
Dim cmd As New MySqlCommand
Dim ad As New MySqlDataAdapter
Dim projeadi As String = "select projects.ID, projects.PROJEADI, projects.TEKLIFFIRMA, details.ID, details.MARKA from projects INNER JOIN details ON projects.ID = details.ID WHERE PROJEADI='" & TextBox1.Text & "';"
Dim tbl As New DataTable
Dim i As Integer
With cmd
.CommandText = projeadi
.Connection = con
End With
With ad
.SelectCommand = cmd
.Fill(tbl)
End With
For i = 0 To tbl.Rows.Count - 1
With ListView1
.Items.Add(tbl.Rows(i)("ID"))
With .Items(.Items.Count - 1).SubItems
.Add(tbl.Rows(i)("PROJEADI"))
.Add(tbl.Rows(i)("TEKLIFFIRMA"))
.Add(tbl.Rows(i)("MARKA"))
End With
End With
Next
ElseIf TextBox2.Text <> "" Then
Dim cmd As New MySqlCommand
Dim ad As New MySqlDataAdapter
Dim tekliffirma As String = "select projects.ID, projects.PROJEADI, projects.TEKLIFFIRMA, details.ID, details.MARKA from projects INNER JOIN details ON projects.ID = details.ID WHERE TEKLIFFIRMA='" & TextBox2.Text & "';"
Dim tbl As New DataTable
Dim i As Integer
With cmd
.CommandText = tekliffirma
.Connection = con
End With
With ad
.SelectCommand = cmd
.Fill(tbl)
End With
For i = 0 To tbl.Rows.Count - 1
With ListView1
.Items.Add(tbl.Rows(i)("ID"))
With .Items(.Items.Count - 1).SubItems
.Add(tbl.Rows(i)("PROJEADI"))
.Add(tbl.Rows(i)("TEKLIFFIRMA"))
.Add(tbl.Rows(i)("MARKA"))
End With
End With
Next
ElseIf TextBox3.Text <> "" Then
Dim cmd As New MySqlCommand
Dim ad As New MySqlDataAdapter
Dim marka As String = "select projects.ID, projects.PROJEADI, projects.TEKLIFFIRMA, details.ID, details.MARKA from projects INNER JOIN details ON projects.ID = details.ID WHERE MARKA='" & TextBox3.Text & "';"
Dim tbl As New DataTable
Dim i As Integer
With cmd
.CommandText = marka
.Connection = con
End With
With ad
.SelectCommand = cmd
.Fill(tbl)
End With
For i = 0 To tbl.Rows.Count - 1
With ListView1
.Items.Add(tbl.Rows(i)("ID"))
With .Items(.Items.Count - 1).SubItems
.Add(tbl.Rows(i)("PROJEADI"))
.Add(tbl.Rows(i)("TEKLIFFIRMA"))
.Add(tbl.Rows(i)("MARKA"))
End With
End With
Next
End If
Please advise.
Thank you.
Oguz
Well, since i don't know whats the name of the table field which corresponds to the checkboxes filter criteria, i'm supposing that it is Projects.Sistem
I would group all checkboxes into a GroupBox in order to use a For loop to check them all. If any of them is checked, an AND clause will be added to the end of your SQL statement.
Once done, another For will check every checked CheckBox to add the Name of the checkbox to your final SQL statement in order to obtain a SQL statement like this
SELECT projects.ID, projects.PROJEADI, projects.TEKLIFFIRMA, details.ID,
details.MARKA from projects INNER JOIN details ON projects.ID = details.ID
WHERE ..... AND Projects.Sistem IN ('FAS', 'VAPA', 'CCTV',.....)
The below code is only an approximation. You will need to check it and adapt it to your existing code
Dim SQL As String = ""
If projeadi <> "" Then
SQL = projeadi
End If
If tekliffirma <> "" Then
SQL = tekliffirma
End If
If marka <> "" Then
SQL = marka
End If
For Each chkBox As CheckBox in GroupBox1.Controls
If chkBox.Checked = True Then
SQL = SQL & " AND Project.Sistem IN ( "
Exit For
End if
Next
For Each chkBox As CheckBox In GroupBox1.Controls
If chkBox.Checked = True Then
Sql = Sql & "'" & chkBox.Name & "',"
End If
Next
Sql = Sql.Substring(0, Sql.Length - 1)
Sql = Sql & ")"

How do I generate a new Primary Key ID through code?

So basically I'm trying to write the below code to the database and I have the primary key as an Int and it was autogen but when writing to the database it didnt allow me to do it kept telling me that I wasn't allowed to enter a null value (because the code is obviously not writing to the primary key field) so I used the line
cmd.Parameters.Add("#EventID", SqlDbType.Int).Value = 3
But the problem is I have to change the value each time I want to test a new record i.e. 1,2,3,4 and so on. I was wondering is there a line of code I can put in to make it create a value by adding +1 each time so I don't need to go into the code and enter a new number each time. Below is the full code writing to the database so you can see a better view of it
Dim Con As SqlConnection
Dim cmd As SqlCommand
Dim recordsAffected As String
Dim cmdstring As String = "INSERT [Event Table](EventID, EventTypeID, EventName, VenueName, NumberOfGuests, Date, ClientAddress, WeddingName, BuildingAddress) Values(#EventID, #EventTypeID, #EventName, #VenueName, #NumberOfGuests, #Date, #ClientAddress, #WeddingName, #BuildingAddress)"
Con = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\YellowDoor.mdf;Integrated Security=True;User Instance=True")
cmd = New SqlCommand(cmdstring, Con)
cmd.Parameters.Add("#EventID", SqlDbType.Int).Value = 3
cmd.Parameters.Add("#EventTypeID", SqlDbType.Text).Value = EventTypeDD.SelectedValue
cmd.Parameters.Add("#EventName", SqlDbType.Text).Value = EventNametxt.Text
cmd.Parameters.Add("#VenueName", SqlDbType.Text).Value = VenueLoDD.SelectedValue
cmd.Parameters.Add("#NumberOfGuests", SqlDbType.Int).Value = CInt(NumOfGtxt.Text)
cmd.Parameters.Add("#Date", SqlDbType.Int).Value = CInt(DateTxt.Text)
cmd.Parameters.Add("#ClientAddress", SqlDbType.Text).Value = txtAddress.Text
cmd.Parameters.Add("#WeddingName", SqlDbType.Text).Value = txtWedding.Text
cmd.Parameters.Add("#BuildingAddress", SqlDbType.Text).Value = txtBAddress.Text
Con.Open()
recordsAffected = cmd.ExecuteNonQuery
Con.Close()
If your EventID is an IDENTITY column, you should never try to set a value for it.
Just ignore that field both as parameter or inside the INSERT command.
And you can retrieve the value assigned by the database engine to your field in this way
Dim Con As SqlConnection
Dim cmd As SqlCommand
Dim cmdstring As String = "INSERT [Event Table] " & _
"(EventTypeID, EventName, VenueName, NumberOfGuests, [Date], ClientAddress, " & _
"WeddingName, BuildingAddress) Values(#EventTypeID, #EventName, #VenueName, " & _
"#NumberOfGuests, #Date, #ClientAddress, #WeddingName, #BuildingAddress); " & _
"SELECT SCOPE_IDENTITY()"
Using Con = New SqlConnection(".....")
Using cmd = New SqlCommand(cmdstring, Con)
cmd.Parameters.Add("#EventTypeID", SqlDbType.Text).Value = EventTypeDD.SelectedValue
.....
Con.Open()
Dim result = cmd.ExecuteScalar()
if result IsNot Nothing Then
Dim newEventID = Convert.ToInt32(result)
....
End If
End Using
End Using
With this code you don't pass anything for the EventID field but you add a second command text to your query. This second command will return the last value generated for an IDENTITY column by the database for your connection. This double command (A.K.A. batch commands) is executed using ExecuteScalar because we are interested in the single value returned by the SELECT SCOPE_IDENTIY()
Notice also that DATE is a reserved word in T-SQL so it is possible to use it as name of a column only if you enclose it in square brackets

How to export data into a word document, not the SQL Query? VB.NET

I have been having a difficult time trying to figure this out. I wrote a SQL query to select certain data that has a relationship to a particular institution. Now the SQL query works perfectly fine as I tested it in MySQL Workbench, however, when I try to export that data from VB.NET onto a word document, it literally prints out the SQL.
Below is my code:
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim sqlTable As New DataTable
Dim sqlFundText As String = "select mutual_Fund_name, concat(contact_first_name,' ',contact_last_name) from mutual_fund mf, contact c, mutual_fund_has_contact mfhc, institution i, institution_has_mutual_Fund ihmf where mf.mutual_fund_id = mfhc.mutual_fund_id and c.contact_id = mfhc.contact_id and ihmf.mutual_fund_id = mf.mutual_fund_id and i.institution_id = ihmf.institution_id and i.institution_name ='" & InstitutionNameTextBox.Text & "' order by mutual_fund_name;"
With sqlCommand
.CommandText = sqlFundText
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(sqlTable)
End With
oPara9 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\endofdoc").Range)
With oPara9
.Range.Font.Bold = False
.Range.Text = sqlFundText
.Range.Font.Size = 10
.Format.SpaceAfter = 5
.Range.InsertParagraphAfter()
End With
And the result is:
As you can see it prints out the SQL statement.
I know it has to do with the
.Range.Text = sqlFundText
I just do not know how to fix it. Can anyone direct me the right way in fixing this?
The data from your query is in sqlTable. You'll need to extract the data from the data table and add that to your document instead of sqlFundText.
After your With sqlAdapter ... End With block you'll need to do something like:
Dim fundName as String
Dim contactName as String
For Each row in sqlTable.Rows
fundName = row[0].ToString()
contactName = row[1].ToString()
' Do something to put fundName and contactName into the document
Next
Here is a Sub() that accepts SQL and returns CSV. It isn't bullet proof but it works for my utility code.
In your case you could use tab as delimiter so that once the data is present in Word it can easily be converted to a table manually.
Yu could also use the code to create/populate a table in Word.
Function CSVReportFromSQL(SQL As String, Optional ToFilePath As String = "") As String
' note return differences if ToFilePath is provided
' If ToFilePath: check for 'OK' on return
' Else check return length = 0 for error
Try
Dim sOut As String = ""
Using con As New SqlConnection(g.OISConnectString)
Dim command As New SqlCommand(SQL, con)
con.Open()
' column headers
Dim rdr As SqlDataReader = command.ExecuteReader(CommandBehavior.SchemaOnly)
For i As Integer = 0 To rdr.FieldCount - 1
sOut &= "," & rdr.GetName(i)
Next
sOut = sOut.Substring(1) & vbCrLf
rdr.Close()
rdr = command.ExecuteReader()
While rdr.Read()
For i As Integer = 0 To rdr.FieldCount - 1
'Debug.Print(rdr.GetFieldType(i).Name & " " & rdr.GetName(i))
'http://msdn.microsoft.com/en-us/library/4e5xt97a(v=vs.80).aspx
Select Case rdr.GetFieldType(i).Name
Case "String", "DateTime"
sOut &= """" & rdr(i).ToString.Replace("""", """""") & ""","
Case Else
sOut &= rdr(i).ToString & ","
End Select
Next
sOut &= vbCrLf
End While
rdr.Close()
End Using
If ToFilePath.Length > 0 Then
My.Computer.FileSystem.WriteAllText(ToFilePath, sOut, False)
Return "OK"
Else
Return sOut
End If
Catch ex As Exception
If ToFilePath.Length > 0 Then
Return ex.Message
Else
MsgBox("Problem creating CSV Report" & vbCrLf & ex.Message)
Return ""
End If
End Try
End Function