Show my data from SSMS SQL into Visual Studio 2012 Datagrid View? - sql

So I have this code in my form but when I try to click the search button to search for a name and show it into my datagrid view using the details from my sql database, it brings nothing. Just blank datagrid.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Dim tblClientDetails As New DataTable
If CON.State = ConnectionState.Closed Then
CON.Open()
End If
With cmd
.Connection = CON
.CommandText = "select * from tblClientDetails where name = #name"
.CommandType = CommandType.Text
.Parameters.AddWithValue("#name", TextBox1.Text)
dr = .ExecuteReader
End With
While (dr.Read)
DataGridView1.DataSource = tblClientDetails
End While
My data in sql which i want to be shown in my datagrid below after searching from a textbox
http://i.stack.imgur.com/3J9lh.png
My form's data grid looks like this;
http://i.stack.imgur.com/QxmF5.png

try this..
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sqlCmd As New SqlCommand()
If CON.State = ConnectionState.Closed Then
CON.Open()
End If
sqlCmd.CommandText = "select * from tblClientDetails where name = #name"
sqlCmd.Connection = CON
sqlCmd.Parameters.AddWithValue("#name", TextBox1.Text)
Dim dr As SqlDataReader = sqlCmd.ExecuteReader()
Dim tblClientDetails As New DataTable()
tblClientDetails.Load(dr)
DataGridView1.DataSource = objDataTable
DataGridView1.DataBind()
CON.Close()
End Sub
Sample example to load a data reader to your data table and then data table to your grid is shown below.
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs)
If Not Page.IsPostBack Then
Dim MyConnection As SqlConnection
Dim MyCommand As SqlCommand
Dim MyDataTable As DataTable
Dim MyReader As SqlDataReader
Dim CityParam As SqlParameter
MyConnection = New SqlConnection()
MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings("DSN_Northwind").ConnectionString
MyCommand = New SqlCommand()
MyCommand.CommandText = " SELECT * FROM CUSTOMERS WHERE CITY = #CITY "
MyCommand.CommandType = CommandType.Text
MyCommand.Connection = MyConnection
CityParam = New SqlParameter()
CityParam.ParameterName = "#CITY"
CityParam.SqlDbType = SqlDbType.VarChar
CityParam.Size = 15
CityParam.Direction = ParameterDirection.Input
CityParam.Value = "London"
MyCommand.Parameters.Add(CityParam)
MyCommand.Connection.Open()
MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection)
MyDataTable = New DataTable()
MyDataTable.Load(MyReader)
gvCustomers.DataSource = MyDataTable
gvCustomers.DataBind()
MyDataTable.Dispose()
MyCommand.Dispose()
MyConnection.Dispose()
End If
End Sub
Source available here

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.

Setting a variable to the highest value in Access Database ASP.NET

I want to set a variable to a value in an Access Database table from aspx.vb. I want to return the highest "PalletNumber" to txbPalletNumber textbox. What am I doing wrong?
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim conn As New OleDbConnection
Dim connString As String
Dim cmd As New OleDbCommand
Try
' Set the connection string.
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\Users\SF7\Desktop\Shore Fresh Logistics_be_be.accdb"
' Open the connection.
conn.ConnectionString = connString
conn.Open()
'Set the command properties.
cmd.Connection = conn
cmd.CommandText = "SELECT PalletNumber, MAX(PalletNumber) FROM
tblPalletNumber"
txbPalletNumber.Text = cmd.ExecuteScalar()
conn.Close()
GridView1.DataBind()
Catch ex As Exception
'Error handling
End Try
txbPackday.Text = DateAndTime.Now
End Sub
Here is the solution. Thanks for all the help.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim conn As New OleDbConnection
Dim connString As String
Dim test As String
' Set the connection string.
connString = "Provider=Microsoft.ACE.OLEDB.12.0;DataSource=C:\Users\SF7\Desktop\Shore Fresh Logistics_be_be.accdb"
' Open the connection.
conn.ConnectionString = connString
conn.Open()
Dim cmd As New OleDbCommand
'Set the command properties.
cmd.Connection = conn
cmd.CommandText = "SELECT MAX(PalletNumber) FROM tblPalletNumber"
test = cmd.ExecuteScalar()
txbPalletNumber.Text = cmd.ExecuteScalar()
conn.Close()
GridView1.DataBind()
txbPackday.Text = DateAndTime.Now
End Sub

Cascading ComboBoxes

I am trying to create a cascading ComboBox that is populated from a SQL data set.
My problem is I am not getting any errors when compiling the code. but the two ComboBoxes are not populating as intended with data. Can you help me find where I am making the mistake?
Private Sub FillSalesPerson()
Dim strConnString As String
strConnString = ConfigurationManager.ConnectionStrings("con").ConnectionString
Dim DS As New SqlConnection(strConnString)
Dim cmd As New SqlCommand()
cmd.Connection = DS
cmd.CommandType = CommandType.Text
cmd.CommandText = "select distinct Name,Salesperson_Code from dbo.View_Customers_With_Sales_People"
Dim objeDS As DataSet = New DataSet()
Dim dAdapter As New SqlDataAdapter
dAdapter.SelectCommand = cmd
DS.Open()
dAdapter.Fill(objeDS)
DS.Close()
ComboBox1.ValueMember = "Salesperson_Code"
ComboBox1.DisplayMember = "Name"
ComboBox1.DataSource = objeDS.Tables(0)
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
If ComboBox1.SelectedValue.ToString() <> " " Then
Dim Salesperson_Code As Integer = Convert.ToInt32(ComboBox1.SelectedValue.ToString())
FillStates(Salesperson_Code)
'ComboBox2.SelectedIndex = 0'
End If
End Sub
Private Sub FillStates(Salesperson_Code As Integer)
Dim strConnString As String = ConfigurationManager.ConnectionStrings("con").ConnectionString
Dim DS As New SqlConnection(strConnString)
Dim cmd As New SqlCommand()
cmd.Connection = DS
cmd.CommandType = CommandType.Text
cmd.CommandText = "Select [No_],[Company Name] from [dbo].[View_Customers_With_Sales_People] where (Salesperson_Code= #Salesperson_Code)"
cmd.Parameters.AddWithValue("#Salesperson_Code", Salesperson_Code)
Dim objDs As New DataSet()
Dim adapter As New SqlDataAdapter()
adapter.SelectCommand = cmd
DS.Open()
adapter.Fill(objDs)
DS.Close()
If objDs.Tables(0).Rows.Count > 0 Then
ComboBox2.ValueMember = "[No_]"
ComboBox2.DisplayMember = "[Company Name]"
ComboBox2.DataSource = objDs.Tables(0)
End If
End Sub
Try changing ComboBox1.DataSource = objeDS.Tables(0) for ComboBox1.RowSource = objeDS.Tables(0)

specified cast is not valid

Here is a code that retrieve values from the database, but my problem is that it throws out an exception saying "InvalidCastException was unhandled specified cast is not valid". I am now confused what went wrong, The code and the table stated below.
Here is the code:
Public connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source =" & Application.StartupPath &
"\TestData.accdb; Persist Security info = false"
Public Conn As New OleDbConnection
Private Sub TestForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Loard
Conn.ConnectionString = connstring
Conn.Open()
LoadValue( )
End Sub
Private Sub LoadValue( )
Dim i As Integer
Dim cmd As OleDbCommand = New OleDbCommand
With cmd
.CommandText = "SELECT MAX(Guard_ID) FROM Guard"
.CommandType = CommandType.Text
.Connection = Conn
.ExecuteNonQuery()
Dim reader As OleDbDataReader = cmd.ExecuteReader
If reader.Read Then
TextBox1.Text = reader.GetString(0)
i = TextBox1.Text + 1
TextBox1.Text = i
reader.Close()
End If
End With
End Sub
The table reference:
Exception Error:
I am really confused now on why the code does not work, any help and advice will be gladly accepted. Thanks in advance.
try this,
Private Sub LoadValue()
Dim i As Integer
Dim cmd As OleDbCommand = New OleDbCommand
With cmd
.CommandText = "SELECT MAX(Guard_ID) FROM Guard"
.CommandType = CommandType.Text
.Connection = Conn
.ExecuteNonQuery()
Dim reader As OleDbDataReader = cmd.ExecuteReader
If reader.Read Then
Dim tmpVal As Object = reader.Item(0)
TextBox1.Text = IIf(IsDBNull(tmpVal), "0", tmpVal.ToString())
i = CInt(TextBox1.Text) + 1
TextBox1.Text = i.ToString()
reader.Close()
End If
End With
End Sub