How do i add data to dataGrid view in VB.net (I'm using WPF dataGrid).
Here is a code that works, this code is for login, my application can access database and i can manipulate data:
Public Function login(ByVal username As String, ByVal password As String)
Try
ManageConnection(False) 'Open connection'
Dim strQuery As String = "SELECT * FROM `dbns`.`wrks` WHERE `username` = '" + username + "' and password = '" + password + "'"
Dim SqlCmd As New MySqlCommand(strQuery, dbCon)
Dim reader As MySqlDataReader = SqlCmd.ExecuteReader()
If reader.HasRows Then
Return True
Else
Return False
End If
reader.Close()
Catch ex As MySqlException
Console.WriteLine("Error: " & ex.ToString())
Finally
ManageConnection(True)
End Try
Return False
End Function
How would i implement a SELECT * FROM xxxxx WHERE xxxx and populate
<DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Margin="376,167,0,0" VerticalAlignment="Top" Height="100" Width="645"/>
This is my Sub for opening and closing connection:
Public Sub ManageConnection(ByVal CloseConnection As Boolean)
Try
'Pripremanje konekcije i upita'
dbCon = New MySqlConnection("server=127.0.0.1;user id=root;password=*****;database=****")
If CloseConnection = False Then
If dbCon.State = ConnectionState.Closed Then _
dbCon.Open()
Else
dbCon.Close()
End If
Catch ex As Exception
MsgBox("Nije moguća konekcija na udaljenu bazu podataka, koristi drugu opciju.")
End Try
End Sub
I want to know if i can use my existing function for connecting to database for datagrid specific needs.
In example:
Public Function testniQuery()
Dim queryString As String =
"SELECT * FROM table"
Dim adapter As SqlDataAdapter = New SqlDataAdapter(
queryString, connection)
Dim customers As DataSet = New DataSet
adapter.Fill(customers, "Customers")
End Function
I do not know Visual Basic that well because I work with C# but the Common Library Runtime (CLR) makes it easier to understand both languages.
When you are connected to MySQL, run your query which you will use DataAdapter to get the data from the query.
The result of the query can be saved in a DataTable and you can easily bind the DataTable to the DataGrid.
So, you run one query and you can use that table persistently in your code.
I do this is C#.
Please bear with C# code. This is a method that will do it
public DataTable Login(string username, string password){
//"SELECT * FROM `dbns`.`wrks` WHERE `username` = '" + username + "' and password = '" + password + "'"
string query = "SELECT * FROM wrks WHERE username = #username AND password = #password";
DataTable table = new DataTable();
using (MySQlConnection connection = new MySQlConnection(connectionString))
{
using (MySqlDataAdapter adapter = new MySqlDataAdapter(query, connection))
{
adapter.SelectCommand.Parameters.AddWithValue("#username", username);
adapter.SelectCommand.Parameters.AddWithValue("#password", password);
adapter.Fill(table);
return table;
}
}
}
The DataTable returned can then be binded to the DataGrid as shown below:
dataGrid1.DataSource = Login("username", "password").DefaultView;
dataGrid1.DataBind();
Related
How to Connection all my forms using only one time setup database?
what's happening to me now is every form i made i always put my database connection
Create a module and make a shared function that you can call it from anywhere.
to get data to your dataset call it from anywhere within your project
Try
Dim dsEmployee As New DataSet()
dsEmployee = ExecuteDataSet("select * from tblEmployee")
Catch ex As Exception
MessageBox.Show("Getting error while getting dataset. " + ex.Message.ToString(), "Data Base", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
for insert records to your database
ExecuteNonQuery("insert into tblEmployee(Emp_ID,Emp_Code,Emp_Name,Emp_Mobile)values(1,'EMP1','Anand','+91 98000000')")
Create a module and make all required function and put your database connection string to MyConnection string vaiable
Option Explicit On
Imports System.Data.SqlClient
Module dbConnect
Dim MyConnection As String = "data source=MyPc;Initial Catalog=TestDb;User ID=sa;Password=12345;"
Public Function ExecuteDataSet(ByVal _Query As String) As DataSet
Dim dsReturn As New DataSet
Try
Dim conn As String = MyConnection
Using con = New SqlConnection(conn)
con.Open()
Dim cmd1 As New SqlCommand(_Query)
cmd1.Connection = con
Dim da As New SqlDataAdapter(cmd1)
dsReturn = New DataSet
da.Fill(dsReturn)
con.Close()
End Using
Catch ex As Exception
MessageBox.Show("Error While Getting DataSet :" + vbNewLine + ex.Message.ToString(), " ERROR ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Return dsReturn
End Function
Public Function ExecuteNonQuery(ByVal _Query As String) As Integer
Dim res As Integer = 0
Try
Dim conn As String = MyConnection
Using con = New SqlConnection(conn)
Dim cmd = New SqlCommand()
cmd.Connection = con
con.Open()
cmd.CommandText = _Query
cmd.Connection = con
res = cmd.ExecuteNonQuery
con.Close()
End Using
Catch ex As Exception
MessageBox.Show("Error While Inserting Records :" + vbNewLine + ex.Message.ToString(), " ERROR ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Return res
End Function
End Module
I have a BackGroundWorker that fetches data in mySQL to be viewed inside a DataGridView. In my DoWork Event
connection()
Try
conn.Open()
Dim query As String
query = "SELECT column02 AS 'Company ID', column05 AS Lastname,
column06 AS Firstname, column07 AS Middlename,
column04 AS 'Contact No.', column13 AS 'Area'
FROM table01
WHERE column10 = '" & selectedAccount & "'
AND column18 = 'Yes'"
command = New MySqlCommand(query, conn)
dataAdapter.SelectCommand = command
dataAdapter.Fill(dataTable)
bSource.DataSource = dataTable
DataGridView_Accounts.DataSource = bSource
For i As Integer = 0 To dataTable.Rows.Count - 1
dataTable.Rows(i)("Company ID") = dataTable.Rows(i)("Company ID")
dataTable.Rows(i)("Lastname") = dataTable.Rows(i)("Lastname")
dataTable.Rows(i)("Firstname") = dataTable.Rows(i)("Firstname")
dataTable.Rows(i)("Middlename") = dataTable.Rows(i)("Middlename")
dataTable.Rows(i)("Contact No.") = dataTable.Rows(i)("Contact No.")
dataTable.Rows(i)("Area") = dataTable.Rows(i)("Area")
Next
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
conn.Dispose()
End Try
It is throwing me errors in my DataGridView about Cross-Threading.
I have tried to move this to the RunWorkerCompleted event
DataGridView_Accounts.DataSource = bSource
For i As Integer = 0 To dataTable.Rows.Count - 1
dataTable.Rows(i)("Company ID") = dataTable.Rows(i)("Company ID")
dataTable.Rows(i)("Lastname") = dataTable.Rows(i)("Lastname")
dataTable.Rows(i)("Firstname") = dataTable.Rows(i)("Firstname")
dataTable.Rows(i)("Middlename") = dataTable.Rows(i)("Middlename")
dataTable.Rows(i)("Contact No.") = dataTable.Rows(i)("Contact No.")
dataTable.Rows(i)("Area") = dataTable.Rows(i)("Area")
Next
There are no more errors about Cross-Threading, but I can't view the result in my DataGridView. It is empty even if my database is filled. Thanks
See if this gets you closer to working...
Imports MySql.Data
Public Class Form1
Private Const ConnectionString As String = ""
' This probably comes from the form but OP did not share that with us.
Private selectedAccount As String = ""
Private dataTable As New DataTable
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Task.Run(Sub() DoWork())
End Sub
Private Sub DoWork()
Dim query As String = "SELECT column02 AS 'CompanyID', column05 AS Lastname,
column06 AS Firstname, column07 AS Middlename,
column04 AS 'ContactNo', column13 AS 'Area'
FROM table01 WHERE column10 = #selectedAccount AND column18 = 'Yes'"
Using MySqlConnection As New MySqlClient.MySqlConnection(ConnectionString)
Dim MySqlCommand As New MySqlClient.MySqlCommand(query, MySqlConnection)
' Use Parameters to avoid vulnerability to SQL Injection
MySqlCommand.Parameters.Add("#selectedAccount", MySqlClient.MySqlDbType.String)
MySqlCommand.Parameters("#selectedAccount").Value = selectedAccount
Using MySqlDataAdapter As New MySqlClient.MySqlDataAdapter(MySqlCommand)
MySqlDataAdapter.Fill(dataTable)
End Using
End Using
RefreshGrid()
End Sub
Sub RefreshGrid()
If Me.InvokeRequired Then
' Shift this call to the UI thread
Me.Invoke(Sub() RefreshGrid())
Else
bSource.DataSource = dataTable
DataGridView_Accounts.DataSource = bSource
DataGridView_Accounts.Refresh()
End If
End Sub
End Class
Honestly, "pretty names" should be set in the DGV, not the SQL, but that's for another topic and I didn't chase this solution that far.
I'm trying to load data into text field from two table in mysql database, but it won't load
Here is my code
Private Sub LoadData()
connString = "Server=Localhost;Database=smart_parking;User Id=root;password="
conn = New MySqlConnection(connString)
conn.Open()
sql = "select a.*, k.* from a anggota, k kendaraan where a.id_card = '" + ComboId.Text + "'"
Dim SqlCommand As New MySqlCommand(sql, conn)
reader = SqlCommand.ExecuteReader
Try
reader.Read()
TxtKartu.Text = reader.GetString(0)
TxtId.Text = reader.GetString(1)
TxtNama.Text = reader.GetString(2)
TxtAlamat.Text = reader.GetString(3)
TxtUmur.Text = reader.GetString(4)
TxtPekerjaan.Text = reader.GetString(5)
Catch ex As Exception
MsgBox(ex)
End Try
conn.Close()
End Sub
it didn't say anything, just can't load any data to the text field. But if I use only one table, it worked perfectly.
Anyone know what the problem is ? Thanks in advance
The following is my code for forgot password,
I want to store the value of mysql query in a variable so that i can use the variable value for placing it in a email.
Private Sub Button3_Click(sender As Object, e As EventArgs)
Handles Button3.Click
Dim p_text As String
p_text = TextBox1.Text
MsgBox(p_text)
Dim i As Integer
Try
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString ="server=192.168.1.111;userid=betterhomes;
password=123456;database=betterhomes"
conn.Open()
Dim password As String = ""
Dim sqlquery2 As String = "SELECT bh_password FROM bh_login
where job_id = '" & p_text & "';"
Dim data2 As MySqlDataReader
Dim adapter2 As New MySqlDataAdapter
Dim command2 As New MySqlCommand
command2.CommandText = sqlquery2
command2.Connection = conn
adapter2.SelectCommand = command2
data2 = command2.ExecuteReader
While data2.HasRows
password = data2.GetString("bh_password")
MsgBox(password)
data2.Close()
End While
Catch exError As MySqlException
' MsgBox("Error connecting to database! Try again later")
End Try
End Sub
End Class
Try Like this
If data2.Read
password = data2.GetString("bh_password")
MsgBox(password)
End if
data2.Close()
Send Email
Dim mail As New MailMessage()
'set the addresses
mail.From = New MailAddress("xx#xx")
mail.[To].Add("xx#xx")
' //set the content
mail.Subject = "This is an email"
mail.Body = password
' // set the server
Dim smtp As New SmtpClient("localhost")
' // send the message
Try
smtp.Send(mail)
Response.Write("Your Email has been sent sucessfully - Thank You")
Catch exc As Exception
Response.Write("Send failure: " & exc.ToString())
End Try
I'm trying to add titles (picture) from all rows to a listbox and I'm getting this error:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll. Not sure what to do at this point I've tried adding functions, making it a variable called item..
Public Function updatenews()
Dim MySqlConnection As New MySqlConnection()
Dim newsmydatatable As New DataTable
Dim rowcount As Integer = 0
Dim amount As Integer
MySqlConnection.ConnectionString = "server=" + host + "; user id=" + user + "; password=" + password + "; database=website;"
Try
MySqlConnection.Open()
Catch myerror As MySqlException
MessageBox.Show("Cannot connect news server: " & myerror.Message & "Please check your internet connection settings and try again. If problem persists contact support.")
Label3.Text = "Error!"
End Try
Dim myadapter As New MySqlDataAdapter
Dim newsmydatatable As New DataTable
Dim sqlquary = "SELECT * FROM news;"
Dim command As New MySqlCommand
command.Connection = MySqlConnection
command.CommandText = sqlquary
myadapter.SelectCommand = command
myadapter.Fill(newsmydatatable)
Dim mydata As MySqlDataReader
mydata = command.ExecuteReader()
If mydata.HasRows = 0 Then
Else
amount = newsmydatatable.Rows.Count
MsgBox(amount)
For value As Integer = 0 To amount
For value As Integer = 0 To amount
ListBox1.Items.Add(newsmydatatable.Rows(rowcount).Item("title"))
rowcount += 1
Next
End If
End Function
where you have:
ListBox1.Items.Add(newsmydatatable.Rows(rowcount).Item("title"))
rowcount += 1
change it to:
ListBox1.Items.Add(newsmydatatable.Rows(value).Item("title"))