how to retrieve data from autocomplete textbox - sql

I am working on a stock management system and i added textbox with autocomplete codes..i have two forms one is items form and other is stock in. now i can able to get itemcodeID from stockin itemnumber textbox with autocomplete codes but when i select that item number its not giving me the description..i mean to say that if user search itemcode in stock in form then he should get description and quantity of that item automatically... i am using vb.net and ms sql .
my code for autocomplete
Private Sub getData(ByVal dataCollection As AutoCompleteStringCollection)
Dim connetionString As String = Nothing
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter()
Dim ds As New DataSet()
connetionString = ("Server= DESKTOP-QN6F623; Database = dbo_main;Integrated Security = false;User ID=dis;Password=0m3rP#ss")
Dim sql As String = "SELECT itemnumber FROM items"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
connection.Close()
For Each row As DataRow In ds.Tables(0).Rows
dataCollection.Add(row(0).ToString())
Next
Catch ex As Exception
MessageBox.Show("Can not open connection ! ")
End Try
End Sub
Private Sub stockin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Stockin_itemnumberTextBox.AutoCompleteMode = AutoCompleteMode.Suggest
Stockin_itemnumberTextBox.AutoCompleteSource = AutoCompleteSource.CustomSource
Dim DataCollection As New AutoCompleteStringCollection()
getData(DataCollection)
Stockin_itemnumberTextBox.AutoCompleteCustomSource = DataCollection
End Sub
i need....when user write in itemnumber textbox he should get related details automatically related to that number...itemnumber of textbox is autocomplete .

Related

how can I Filter my Datagriview?

Hello guys I am beginner and starting to learn codes anyway
I created a form and use datagridview where my database data goes and also i created search textbox and search button. But I want to put a Filter on it so
If a user wants to search the studentname from Diamond class, so they choose Diamon in the first combobox. now they want to search Studentname from Diamon Class whose status is Absent, so they enter Absent in the second text box , and the data grid shows Student from Diamon Class whose status is Absent.
Can you help me please
Im using vb.net 1st programming language and ms access as a beginner?
I don't know how. Can you show me on how to do that
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If ComboBox1.Text = "Diamon" Then
If ComboBox2.Text = "StudentName" Then
Attendance()
End If
End If
End Sub
Public Sub Attendance()
Try
Dim sCon As String = String.Format("Provider= Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\db.accdb")
Dim str As String = "SELECT * FROM dbtable WHERE Attendance = #A1"
Dim dt As New DataTable
Using con1 As OleDbConnection = New OleDbConnection(sCon)
con1.Open()
Using cmd1 As OleDbCommand = New OleDbCommand(str, con1)
With cmd1.Parameters
.Add("#A", OleDbType.VarChar).Value = TextBox1.Text
End With
Dim adp As New OleDbDataAdapter(cmd1)
adp.Fill(dt)
DataGridView1.DataSource = dt
End Using
con1.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

How to feed results of SQL statement into a GridView, not the SQL statement itself?

This has got to be close, but it's been a long day and I'm tired now so I can;t really see what the problem is. Basically, I have a table in SQL Server with 2 columns; one has the names of reports and the other has some SQL Scripts that I want to pass into a GridView, based on what a user selects from a ListBox. Here is my code.
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim sqlConn As New SqlClient.SqlConnection("Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True")
sqlConn.Open()
Dim cmd As New SqlClient.SqlCommand("Select ReportName From [Table_1] order by ReportName", sqlConn)
Dim dsColumns As New DataSet
Dim daAdapter As New SqlClient.SqlDataAdapter(cmd)
daAdapter.Fill(dsColumns)
If dsColumns.Tables(0).Rows.Count > 0 Then
ListBox1.Items.Clear()
For i As Integer = 0 To dsColumns.Tables(0).Rows.Count - 1
ListBox1.Items.Add(dsColumns.Tables(0).Rows(i)(0).ToString())
Next
End If
Catch ex As Exception
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connetionString As String
Dim SqlStr As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim ds As New DataSet
Dim myItem As String
connetionString = "Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True"
connection = New SqlConnection(connetionString)
'Dim iIndex As Integer = ListBox1.SelectedIndex
myItem = ListBox1.SelectedItem
SqlStr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
connection.Open()
adapter = New SqlDataAdapter(SqlStr, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
I guess the problem is passing the SQL to the GridView. When I select the first Item, I see this in my GridView.
SELECT [OrderID]
,[CustomerID]
,[EmployeeID]
,[OrderDate]
,[RequiredDate]
,[ShippedDate]
,[ShipVia]
,[Freight]
,[ShipName]
,[ShipAddress]
,[ShipCity]
,[ShipRegion]
,[ShipPostalCode]
,[ShipCountry]
FROM [Test].[dbo].[Orders]
That's pretty close, but I want to get that SQL fed into the GridView, and get the results of the SQL displayed in the GridView, not eh SQL statement itself.
This is what I see now.
I want to see something more like this.
Finally, I am curious to know of the GridView can be made dynamic, so if I stretch out the window the GridView shows more columns. Now, if I stretch out the form window, the GridView stays static.
You need to actually run the retrieved Sql statement:
sqlstr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
connection.Open()
Dim cmd As New SqlCommand(sqlstr, connection)
Dim sqlstr_report As String = CStr(cmd.ExecuteScalar())
cmd.Dispose()
adapter = New SqlDataAdapter(sqlstr_report, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.DataSource = ds.Tables(0)
Use the .Anchor property of the DataGridView to make it resize with the form

Database not updating via DataGridView

I am trying to update an access database via a DataGridView on vb.net without the use of a wizard.
However, I have encountered two primary issues:
When I attempt to save the content added to the grid, a message box displays the exception from a try catch saying "DataTable already belong to this dataSet".
When I was able to make a changes without an exception the data got saved to the database, however when I later closed an reopened to the database and DataGridView the changes had been undone. Take note that the database has been placed in the bin/Debug folder.
Here is the code for the saving event:
Dim dataAdapter As New OleDbDataAdapter
Dim DataTable As New DataTable
Dim DataSet As New DataSet
Dim Connection As New OleDbConnection
Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
Try
Connection.Open() ' the following decleration are used to save content to the table.
dataSet.Tables.Add(dataTable)
dataAdapter = New OleDbDataAdapter("SELECT * FROM Students", Connection)
dataAdapter.Fill(dataTable)
Dim newRow As DataRow = dataTable.NewRow
With newRow ' the with statement allows you do repeatedly apply a property to a certain object
.Item("StudentID") = txtStudentID.Text ' these statements add the content of the text boxes to these respective fields in the database
.Item("TeacherID") = txtTeacherID.Text
.Item("StudentFirstName") = txtStudentFirstname.Text
.Item("StudentSurname") = txtStudentSurname.Text
.Item("StudentPassword") = txtStudentPassword.Text
.Item("StudentGroup") = cbxStudentGroup.Text
End With
dataTable.Rows.Add(newRow)
DataSet.Tables.Add(DataTable)
Dim Command As New OleDbCommandBuilder(dataAdapter)
dataAdapter.Update(dataTable) 'updates the table
Connection.Close()
ShowItems() ' displays the table
Catch ex As Exception
MessageBox.Show(ex.Message)
Connection.Close()
End Try
End Sub
If any more detail is required do ask.
edit: i found that the first issue is also prevalent when trying to delete something via the dataGrid, here is the code:
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
Try
dataSet.Tables.Add(dataTable)
Connection.Open()
dataAdapter = New OleDbDataAdapter("SELECT * FROM Students", Connection)
dataAdapter.Fill(dataTable)
dataTable.Rows(0).BeginEdit()
dataTable.Rows(0).Delete()
dataTable.Rows(0).EndEdit()
Dim Commandbuilder As New OleDbCommandBuilder(dataAdapter)
dataAdapter.Update(dataTable)
dgrStudentDatabaseViewer.DataSource = dataTable.DefaultView
Connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Connection.Close()
End Try
End Sub
> Public Sub fillDatatable(_datatable As DataTable, Query As String)
> Dim sqlQuery As String = (Query)
> Using conn As New SqlConnection("YourConnectionString")
> conn.Open()
> Using da As New SqlDataAdapter(sqlQuery, conn)
> da.Fill(_datatable)
> End Using
> conn.Close()
> End Using End Sub
Private Sub yourEvent()
Using xDT As New Datatable
fillDatatable(xDT, "Your Query;")
yourDGV.DataSource = sssCompDT
yourDGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
yourDGV.Refresh()
End Using
End Sub
this should open display your sqlQuery results to a datagridview, see if it works on your end :D

VB.NET-A way to insert rows into datagrid or datatable

Hi once again am stuck in middle where i need some pointer.... I need a way fill the datagrid in a for loop...
Dim rs As SqlCommand
Dim dt As New DataTable
For Each line As String In RichTextBox1.Lines
query = "myquery '" & RichTextBox1.Lines(i).ToString & "'"
rs = New SqlCommand(query, Module1.dtsrv_conn)
dt.load(rs.Executereader)
If i < 1 Then
DataGridView1.DataSource = dt
Else
datagridview1.rows.Add(rs.ExecuteReader)
End If
i = i + 1
Next
many lines of text will be entered in RichTextBox and each line need to be compared with values in database and the resulted table need to be shown in datagrid... I tried adding the newly queried row to datagrid directly but it throws exception so i tried to add new row to datatable and load the datagrid later but i cant find a way....
If I understand your question which isn't very clear, the user is entering values that you want to query against rows in your database and if they exist, display some corresponding data or message.
It sounds like what you want to do is bind your datagrid to a datasource, in my example an in-memory datatable, then intercept the data binding via DataGridView1.CellFormatting to compare/modify your data accordingly.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sqlConnection As SqlConnection
Dim sqlConnectionString As String = "YourConnectionString"
Dim sqlDataAdapter As SqlDataAdapter
Dim dataTable As New DataTable
Dim sqlCommand As SqlCommand
Dim sqlString As String
Try
sqlString = "SELECT * FROM YourTable" 'if user input values are filters, loop through and append them in WHERE clause
sqlConnection = New SqlConnection(sqlConnectionString)
sqlCommand = New SqlCommand(sqlString, sqlConnection)
sqlConnection.Open()
sqlDataAdapter = New SqlDataAdapter(sqlCommand)
sqlDataAdapter.Fill(dataTable)
sqlConnection.Close()
DataGridView1.DataSource = dataTable
Catch ex As Exception
'Handle error
End Try
End Sub
Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
If Me.DataGridView1.Columns(e.ColumnIndex).Name = "YourColumnNameToCompare" Then
If e.Value IsNot Nothing Then
'do your comparison to user input text here and if necassary change the value like so..
For Each line In RichTextBox1.Lines
If line = e.Value Then
e.Value = "Value modified"
Exit For
End If
Next
e.FormattingApplied = True
End If
End If
End Sub

Showing all fields in listbox from database, vb.net

I'm trying to make a list box to show all the fields of a particular table in an Access database. I have a few tables, and the idea would be to have each table loaded by a different button (and the items in the box cleared). One trick is that tables aren't all the same size. How do I get all the fields to show up for each table. What I have now is only showing one field:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;data source='C:\dummy_data.accdb';"
Dim conn As New OleDbConnection(connString)
Dim sql As String = "SELECT * FROM Customers"
Dim cmd As New OleDbCommand(sql, conn)
conn.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader()
ClientList.Items.Clear()
While reader.Read()
ClientList.Items.Add(reader(0).ToString())
End While
reader.Close()
conn.Close()
End Sub
If you are not averse to using a DataGridView instead of a ListView, you could do it this way:
Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;data source='PathToMyDatabase';"
Dim sql As String = "SELECT * FROM Tメイン;"
Dim dt As DataTable
With New OleDbDataAdapter(sql, connString)
Dim ds As New DataSet()
.Fill(ds)
dt = ds.Tables(0)
End With
Me.DataGridView1.DataSource = dt
I do not have 'ACE.OLEDB' on my computer, so had to use the JET provider instead, but it should work the same way.
I should add that you can use this method to retrieve the data from the DB, but there is no easy way as far as I understand to bind a DataTable to a ListView (see this MSDN question for example) and you would have to loop through the columns in your DataTable first and add the column headers to your ListView and then loop through the rows and add the data.
UPDATE:
To answer your questiona s to how to export data from the DataGridView I remembered that I wrote code to do that a little while back.
Private Function ExportToExcelFile(ByVal FileName As String) As Boolean
With New Excel.Application
With .Workbooks.Add()
For Each sheet As Worksheet In .Worksheets
If sheet.Index > 1 Then
Call sheet.Delete()
End If
Next
With CType(.Worksheets(1), Worksheet).Range("A1")
For Each column As DataGridViewColumn In Me.dgvData.Columns
.Offset(0, column.Index).Value = column.HeaderText
For Each row As DataGridViewRow In Me.dgvData.Rows
.Offset(row.Index + 1, column.Index).Value = row.Cells(column.Index).Value
Next
Next
End With
Call .SaveAs(FileName)
End With
Call .Quit()
End With
End Function
I hope this will help to get you started.
Using a Listview control, the following code should do the trick. For simplicity I defined only 4 customer fields - you will need to define them according to your table field defintions:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ClientList.View = View.Details
ClientList.FullRowSelect = True
ClientList.Columns.Add("ID", 120)
ClientList.Columns.Add("Name", 120)
ClientList.Columns.Add("Address", 140)
ClientList.Columns.Add("Email", 100)
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\dummy_data.accdb;"
ClientList.Items.Clear()
Using conn As New Data.OleDb.OleDbConnection(connString)
conn.Open()
Dim sql As String = "SELECT * FROM Customers"
Using cmd As New Data.OleDb.OleDbCommand(sql, conn)
Dim lvi As ListViewItem
Using oRDR As Data.OleDb.OleDbDataReader = cmd.ExecuteReader
While oRDR.Read()
lvi = ClientList.Items.Add(oRDR.GetValue(0).ToString)
For i = 1 To oRDR.FieldCount - 1
lvi.SubItems.Add(oRDR.GetValue(i).ToString)
Next
End While
End Using
End Using
conn.Close()
End Using
End Sub