visual basic programming combo box issue - vb.net

How do I use environment.username code on my app to show current system user in the combobox, or to list everyone who ever logged in that pc?
Current code:
Private Sub FrmLogin2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'loading the Computer user account in the current pc
Dim WSHNetwork = CreateObject("WScript.Network")
Dim strUser = ""
strUser = Environment.UserName
lblDispalyWinUser.Text = Environment.UserName
Dim con As SqlConnection = New SqlConnection("Data Source=SRD-WSJHBAP12\CALCTOOL;Initial Catalog=CalcToolDB;User ID=sa;Password=P#ssw0rd")
Dim cmd As SqlCommand = New SqlCommand("Select EmpNo, Username, Password from UserLogin ", con)
Dim sda As SqlDataAdapter = New SqlDataAdapter(cmd)
'Dim dt As DataTable = New DataTable()
Dim ds As New DataSet()
Dim rd As SqlDataReader
con.Open()
con.Close()
Try
con.Open()
sda.Fill(ds)
sda.Dispose()
cmd.Dispose()
con.Close()
'cboUsername.DataSource = ds.Tables(0)
cboUsername.ValueMember = "Environment.UserName"
cboUsername.DisplayMember = "Environment.UserName"
Catch ex As Exception
MessageBox.Show("can not open connection ! ")
End Try

Related

textbox AutoComplete not working after a search query

Hello there I am quite new to windows form programming, and my project requires me to do a search query on my database. I would like the option for the names that can be currently searched to be displayed when typing, however, after pressing the search button the autocomplete no longer displays when I try to look for another attribute. https://i.stack.imgur.com/Wytdy.png , https://i.stack.imgur.com/Qjy5q.png
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(mSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(ds, "customers")
dt = ds.Tables(0)
MaxRows = ds.Tables("customers").Rows.Count
con.Close()
Dim msSQL As String = "SELECT * FROM customers;"
dgvCustomerInfo.DataSource = display(msSQL, "customers")
Try
dt = New DataTable
con.Open()
With cmd
.Connection = con
.CommandText = "SELECT DISTINCT fname FROM customers"
End With
da.SelectCommand = cmd
da.Fill(dt)
Dim r As DataRow
txtSearchName.AutoCompleteCustomSource.Clear()
For Each r In dt.Rows
txtSearchName.AutoCompleteCustomSource.Add(r.Item(0).ToString)
Next
''''''''''''''''''''''''
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
da.Dispose()
I believe your problems stem from the AutoCompleteMode. Suggest and SuggestAppend seem to fill in the text box as expected. Append seem to do nothing. I don't think this is working as intended.
I tested with a little database I have. It is Sql Server but should work the same for Sqlite. I used a bit of Linq magic to get the AutoCompleteCustomSource. A few other changes... Using...End Using blocks ensure that database objects are closed and disposed. You don't need a DataAdapter, just a DataTable and Command.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = GetDataForTextBox()
Dim strArray = dt.AsEnumerable().[Select](Function(x) x.Field(Of String)("Name")).ToArray()
TextBox5.AutoCompleteSource = AutoCompleteSource.CustomSource
Dim MySource As New AutoCompleteStringCollection()
MySource.AddRange(strArray)
TextBox5.AutoCompleteCustomSource = MySource
TextBox5.AutoCompleteMode = AutoCompleteMode.SuggestAppend
End Sub
Private Function GetDataForTextBox() As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select Distinct Name From Coffees", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = GetSearchResults(TextBox5.Text)
DataGridView1.DataSource = dt
End Sub
Private Function GetSearchResults(name As String) As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select * From Coffees Where Name = #Name", cn)
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = name
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function

Multiple DataGridView on TabPages. vb.net

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
abc()
Refresh()
Dim con As String = "Data Source = HCA-ISD03\SQLEXPRESS; Initial Catalog = QMS_HCA; User ID=qs; Password=ZAQ!2wsx; MultipleActiveResultSets=True"
Dim conn As New SqlConnection(con)
Dim Query As String = Nothing
Dim Query2 As String = Nothing
Dim Query3 As String = Nothing
Dim adapter As New SqlDataAdapter
Dim adapter1 As New SqlDataAdapter
Dim ds As New DataSet()
Dim table As New DataTable()
Dim cmd1 As New SqlCommand
Query = "Select sMessage, iAlert FROM MAS_Alert"
Query2 = "SELECT REF_AlertPlate.sPlateNo, MAS_Alert.sMessage, REF_AlertPlate.iAlert, REF_AlertPlate.dStart, REF_AlertPlate.dEnd, REF_AlertPlate.sFrameNo FROM REF_AlertPlate INNER JOIN MAS_Alert ON MAS_Alert.iAlert=REF_AlertPlate.iAlert"
Query3 = "SELECT iAlert, sMessage, dCreated, iCreatedBy FROM MAS_Alert"
Try
conn.Open()
adapter.SelectCommand = cmd
adapter.SelectCommand = New SqlCommand(Query, conn)
adapter.SelectCommand = New SqlCommand(Query2, conn)
adapter.SelectCommand = New SqlCommand(Query3, conn)
adapter.Fill(ds)
adapter.Dispose()
cmd.Dispose()
ComboBox1.Items.Clear()
DataGridView2.DataSource = ds.Tables(0)
DataGridView1.DataSource = ds.Tables(1)
ComboBox1.DataSource = Nothing
ComboBox1.Refresh()
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.ValueMember = "iAlert"
ComboBox1.DisplayMember = "sMessage"
Catch ex As Exception
End Try
conn.Close()
End Sub
How can I load the datagridView1? The only DataGridView that loads is the DataGridView2. Sorry if I'm wrong, I set the three queries in the formload. What should I do first?? The only query that loads is the Query and Query2Thank you in advance mates. Hope that you can help me.
I've created another sub for the DataGridView1 then call it in FormLoad
Sub Query3()
Dim con As String = "Data Source = HCA-ISD03\SQLEXPRESS; Initial Catalog = QMS_HCA; User ID=qs; Password=ZAQ!2wsx; MultipleActiveResultSets=True"
Dim conn As New SqlConnection(con)
Dim Query3 As String = Nothing
Dim adapter As New SqlDataAdapter
Dim adapter1 As New SqlDataAdapter
Dim ds As New DataSet()
Dim table As New DataTable()
Dim cmd1 As New SqlCommand
Query3 = "SELECT iAlert, sMessage, dCreated, iCreatedBy FROM MAS_Alert"
Try
conn.Open()
adapter.SelectCommand = cmd
adapter.SelectCommand = New SqlCommand(Query3, conn)
adapter.Fill(ds)
adapter.Dispose()
cmd.Dispose()
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
End Try
conn.Close()
End Sub
Problem Solved. Sorry if I made a mistake.

Login failed for user ''. error

I know that this is a duplicate post but I couldn't find my solution on that topics. I want to connect my sql file in debug folder but I got error that Login failed for user ''.
Dim connectionString As String = String.Format("Data Source=.\SQLEXPRESS;AttachDbFilename={0}\Word.mdf;Integrated Security=False;Connect Timeout=30;User Instance=True", My.Application.Info.DirectoryPath)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim sql As String = "SELECT * FROM test"
Dim connection As New SqlConnection(connectionString)
Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "test_table")
connection.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "test_table"
MakePivot()
connection.Close()
DataGridView2.ClearSelection()
End Sub
Could you tell me my mistake please?
Dim ds As New DataSet()
Using connection As New SqlConnection(String.Format("Data Source=.\SQLEXPRESS;AttachDbFilename={0}\Word.mdf;Integrated Security=true;Connect Timeout=30;User Instance=True", My.Application.Info.DirectoryPath))
connection.Open()
Using command As New SqlCommand("SELECT * FROM test", connection)
command.CommandTimeout = 0
Using da As New SqlDataAdapter(command)
da.Fill(ds)
End Using
End Using
End Using
DataGridView1.DataSource = ds
MakePivot()
DataGridView2.ClearSelection()
Try this code, need to set "integrated security=true"

Datagridview to CrystalReport Error "Input array is longer than the number of columns in this table."

I am trying to get the datagridview data to Crystal report, but i am getting this ERROR message "Input array is longer than the number of columns in this table."
Any Idea how to fix my error?
Sub PrintToCR()
Dim dt As New DataTable
For Each dr As DataGridViewRow In Me.DataGridView1.Rows
dt.Rows.Add(dr.Cells("ProductID").Value, dr.Cells("BrandName").Value, dr.Cells("GenericName").Value, _
dr.Cells("ExpirationDate").Value, dr.Cells("Price").Value, _
dr.Cells("Unit").Value, dr.Cells("QuantityOnHand").Value) '<<<<< Error is HERE.
Next
'
Dim rptDoc As CrystalDecisions.CrystalReports.Engine.ReportDocument
rptDoc = New CrystalReport1
rptDoc.SetDataSource(dt)
'
CrystalReportViewer.CrystalReportViewer1.ReportSource = rptDoc
CrystalReportViewer.ShowDialog()
CrystalReportViewer.Dispose()
End Sub
this is my Database transaction
Public Class data
Dim connString As New connection
Dim con As New OleDb.OleDbConnection
Dim cmd As New OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Public Function List(ByVal sql As String) As DataSet
con.ConnectionString = connString.connectionString
con.Open()
da = New OleDb.OleDbDataAdapter(sql, con)
Dim ds As New DataSet
da.Fill(ds, "data")
con.Close()
List = ds
End Function
Public Sub ExecuteSql(ByVal sql As String)
con.ConnectionString = connString.connectionString
con.Open()
cmd.CommandText = sql
cmd.CommandType = CommandType.Text
cmd.Connection = con
cmd.ExecuteNonQuery()
con.Close()
End Sub
End Class
Btw, my Datagridview is connected via Datasource
thanks
try this ..
Dim dt As New DataTable
dt.Columns.Add("ProductId")
dt.Columns.Add("BrandName")
dt.Columns.Add("GenericName")
dt.Columns.Add("ExpirationDate")
dt.Columns.Add("Price")
dt.Columns.Add("Unit")
dt.Columns.Add("QuantityOnHand")
For Each dr As DataGridViewRow In Me.DataGridView1.Rows()
dt.Rows.Add(dr.Cells("ProductID").Value, dr.Cells("BrandName").Value, dr.Cells("GenericName").Value, _
dr.Cells("ExpirationDate").Value, dr.Cells("Price").Value, _
dr.Cells("Unit").Value, dr.Cells("QuantityOnHand").Value)
Next
'
Dim rptDoc As CrystalDecisions.CrystalReports.Engine.ReportDocument
rptDoc = New CrystalReport1
rptDoc.SetDataSource(dt)
CrystalReportViewer.CrystalReportViewer1.ReportSource = rptDoc
CrystalReportViewer.ShowDialog()
CrystalReportViewer.Dispose()

MS Access Db not saving in Vb.net

1) I have problem that Code work properly at runtime and update data
grid of windows form .net , but after close the form and when I
check DB , the data not update there , (still the db unchanged )
2) I also have problem after publish , please see the image!
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using con As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\labprofiles.mdb;Persist Security Info=True")
con.Open()
Dim cmd As OleDbCommand = New OleDbCommand("DELETE FROM Mint", con)
cmd.ExecuteNonQuery()
End Using
instrecall()
End Sub
Private Sub instrecall()
Using con As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\labprofiles.mdb;Persist Security Info=True")
con.Open()
Try
Dim cmd As OleDbCommand = New OleDbCommand("UPDATE int SET timespan = #timespan, nextscandue = #next WHERE (type = 'folder')", con)
cmd.Parameters.AddWithValue("#timespan", 20)
Dim nex As String = DateAndTime.Now.AddMinutes(20)
cmd.Parameters.AddWithValue("#next", nex)
cmd.ExecuteNonQuery()
con.Close()
con.Open()
Dim cmd1 As OleDbCommand = New OleDbCommand("INSERT INTO Mint SELECT * FROM int WHERE (type = 'folder')", con)
cmd1.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Using
End Sub
Close your connections once finished....
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using con As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\labprofiles.mdb;Persist Security Info=True")
con.Open()
Try
Dim cmd As OleDbCommand = New OleDbCommand("DELETE FROM Mint", con)
cmd.ExecuteNonQuery()
Catch ex as Exception
MsgBox(ex.ToString())
Finally
con.Close()
End Try
End Using
instrecall()
End Sub
Private Sub instrecall()
Using con As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\labprofiles.mdb;Persist Security Info=True")
con.Open()
Try
Dim cmd As OleDbCommand = New OleDbCommand("UPDATE Mint SET timespan = #timespan, nextscandue = #next WHERE (type = 'folder')", con)
cmd.Parameters.AddWithValue("#timespan", 20)
Dim nex As String = DateAndTime.Now.AddMinutes(20)
cmd.Parameters.AddWithValue("#next", nex)
cmd.ExecuteNonQuery()
con.Close()
con.Open()
Dim cmd1 As OleDbCommand = New OleDbCommand("INSERT INTO Mint SELECT * FROM int WHERE (type = 'folder')", con)
cmd1.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.ToString())
Finally
con.Close()
End Try
End Using
End Sub