how to display data in text box in vb.net using sql - vb.net

Private Sub BtnReturn_Click(sender As Object, e As EventArgs) Handles btnReturn.Click
If BorrowAccession.Text = "" Or txtBorrowerstype.Text = "" Then
MsgBox("All fields are required.", MsgBoxStyle.Exclamation)
ElseIf txtremarks.Text = "Over Due" Then
sql = "Select * From `maintenance` fine ='" & txtfine.Text & "' "
reloadtxt(sql)
End sub
how will i display the fine in txtfine.text from my maintenance database after it satisfy the condition from txtremarks. i tried some youtube tutorials but only displaying it from data grid .. want i basically want is directly display it from database to textbox. btw im newbie in vb programming thank you in advance
for my reloadtxt this is the code.
Public Sub reloadtxt(ByVal sql As String)
Try
con.Open()
With cmd
.Connection = con
.CommandText = sql
End With
dt = New DataTable
da = New MySqlDataAdapter(sql, con)
da.Fill(dt)
Catch ex As Exception
' MsgBox(ex.Message & "reloadtxt")
Finally
con.Close()
da.Dispose()
End Try
End Sub

To populate an object with data from a database you need to access the objects text property.
Textbox1.Text = "Some Text, static or dynamic"
Since you are pulling the data from a datatable you would access the column named "fine" and put that value in the textbox.text property.
Textbox1.Text = dt.row(0).item("fine").tostring

Changed Or to OrElse because it short circuits the If and doesn't have to check the second condition if the first condition is True.
In the reloadtxt method you filled a DataTable and did nothing with it. I changed it to a Function that returns the DataTable. The connection and command are now included in a Using...End Using block so they are closed and disposed even if there is an error.
Never concatenate strings to build an sql statement. Always used parameters.
Private Sub BtnReturn_Click(sender As Object, e As EventArgs) Handles btnReturn.Click
If BorrowAccession.Text = "" OrElse txtBorrowerstype.Text = "" Then
MsgBox("All fields are required.", MsgBoxStyle.Exclamation)
ElseIf txtremarks.Text = "Over Due" Then
Dim dt = reloadtxt()
DataGridView1.DataSource = dt
End If
End Sub
Public Function reloadtxt() As DataTable
Dim dt As New DataTable
Using con As New MySqlConnection("Your connection string"),
cmd As New MySqlCommand("Select * From maintenance Where fine = #Fine", con)
cmd.Parameters.Add(#Fine, MySqlDbType.VarChar, 50).Value = txtfine.Text
Try
con.Open()
dt.Load(cmd.ExecuteReader)
Catch ex As Exception
MsgBox(ex.Message & "reloadtxt")
End Try
End Using
Return dt
End Function

Related

Save a DataGridView data to Access database

I am trying to save a DataGridView data to an Access database (database is already connected to Visual Studio).
Here's my code:
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Try
Dim cn As OleDbConnection
cn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= |DataDirectory|\GEFORSERVI V2.1.accdb;")
cn.Open()
Dim cmd As New OleDbCommand
cmd.Connection = cn
cmd.CommandType = Data.CommandType.Text
Dim Strcommandtext As String = "inserto into Factura(Designacao,PrecoUnitario,Qtd,Total,Nome,Entidade,NIF,Telefone,Morada,CodigoProduto,DataEmissao) VALUES(#Servico_Produto,#Valor,#Qtd,#Total,#Nome,#Entidade,#NIF,#Telemovel,#Bairro,#Data_de_Emissao)"
Dim values As String = ""
For i As Integer = 0 To Factura2DataGridView.Rows.Count - 1
values = Strcommandtext & Factura2DataGridView.Rows(i).Cells(11).Value & ")"
cmd.CommandText = values
cmd.ExecuteNonQuery()
Next i
cmd = Nothing
cn.Close()
MsgBox("Your Record Inserted Successfully ")
Catch myException As Exception
MsgBox("No Record Inserted" + myException.ToString())
Finally
'MsgBox("Closing Connection")
End Try
End Sub
Connections and Commands need to be disposed so they can release unmanaged resources. Using...End Using blocks are the best way to handle this since the will do this even if there is an error. In this code I both the connection and command are included in the Using block. Note the comma at the end of the first Using line.
Pass the CommandText and the Connection directly to the constructor of the command. I noticed you had missed one of the parameters that was in the field list. I also noticed the you typed "inserto". I believe it must be "Insert". It is not necessary to set CommandType since CommandType.Text is the default.
In OleDb the order that the parameters appear in the sql string must match the order that they are added to the Parameters collection.
Build the parameters collection once outside the loop. It is only the Values of the parameters that change in the loop.
Open the connection once, outside the loop.
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Try
Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= |DataDirectory|\GEFORSERVI V2.1.accdb;"),
cmd As New OleDbCommand("Insert into Factura(Designacao,PrecoUnitario,Qtd,Total,Nome,Entidade,NIF,Telefone,Morada,CodigoProduto,DataEmissao)
VALUES(#Servico_Produto,#Valor,#Qtd,#Total,#Nome,#Entidade,#NIF,#Telemovel,#Bairro,#CodigoProduto,#Data_de_Emissao)", cn)
With cmd.Parameters
.Add("#Servico_Produto", OleDbType.Integer)
.Add("#Valor", OleDbType.VarWChar)
.Add("#Qtd", OleDbType.Integer)
.Add("#Total", OleDbType.Decimal)
.Add("#Nome", OleDbType.VarWChar)
.Add("#Entidade", OleDbType.VarWChar)
.Add("#NIF", OleDbType.VarWChar)
.Add("#Telemovel", OleDbType.VarWChar)
.Add("#Bairro", OleDbType.VarWChar)
.Add("#CodigoProduto", OleDbType.Integer)
.Add("#Data_de_Emissao", OleDbType.Date)
End With
cn.Open()
For i As Integer = 0 To Factura2DataGridView.Rows.Count - 1
cmd.Parameters("#Servico_Produto").Value = Factura2DataGridView.Rows(i).Cells(0).Value
cmd.Parameters("#Valor").Value = Factura2DataGridView.Rows(i).Cells(1).Value
cmd.Parameters("#Qtd").Value = Factura2DataGridView.Rows(i).Cells(2).Value
cmd.Parameters("#Total").Value = Factura2DataGridView.Rows(i).Cells(3).Value
cmd.Parameters("#Nome").Value = Factura2DataGridView.Rows(i).Cells(4).Value
cmd.Parameters("#Entidade").Value = Factura2DataGridView.Rows(i).Cells(5).Value
cmd.Parameters("#NIF").Value = Factura2DataGridView.Rows(i).Cells(6).Value
cmd.Parameters("#Telemovel").Value = Factura2DataGridView.Rows(i).Cells(7).Value
cmd.Parameters("#Bairro").Value = Factura2DataGridView.Rows(i).Cells(8).Value
cmd.Parameters("#CodigoProduto").Value = Factura2DataGridView.Rows(i).Cells(9).Value
cmd.Parameters("#Data_de_Emissao").Value = Factura2DataGridView.Rows(i).Cells(10).Value
cmd.ExecuteNonQuery()
Next
End Using
MsgBox("Your Record Inserted Successfully ")
Catch myException As Exception
MsgBox("No Record Inserted" + myException.Message)
End Try
End Sub
There are easier ways to do this. If you have a DataTable bound to the DataGridView you can use a DataAdpater.Update method.

error regular comes Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged, MyBase.Activated
con.Close()
con.Open()
str = "select * from customer where CustomerID='" & ComboBox1.Text & "'"
cmd = New OleDbCommand(str, con)
da.SelectCommand = cmd
If IsNumeric(ComboBox1.Text) Then
cmd.CommandText = str = "select * from customer where CustomerID=#cid"
cmd.Prepare()
cmd.Parameters.AddWithValue("cid", ComboBox1.Text)
Dim dr As OleDbDataReader = cmd.ExecuteReader()
Try
If dr.Read() Then
TextBox1.Text = dr.GetValue(1)
TextBox2.Text = dr.GetValue(2)
TextBox3.Text = dr.GetValue(3)
TextBox4.Text = dr.GetValue(4)
TextBox5.Text = dr.GetValue(5)
dr.Close()
End If
Catch ex As Exception
MsgBox("", ex.Message)
dr.Close()
Finally
con.Close()
End Try
End If
Your code has several issues.
You did not provide your complete Combobox1_SelectedIndexChanged method. At least the last line that ends the method is missing.
You are reusing a connection. It is better practice to create a new connection (and dispose it afterwards) each time you need it. (Connection pooling might already reuse connections in the background.)
You have an exception handling mechanism that doesn't cover all your logic that can throw exceptions.
You are using two approaches to pass the SQL command text to the command object. One approach should suffice.
You call the Prepare method before you add your parameters to the command object. Apart from the fact that calling Prepare probably is not explicitly needed, I guess it should be called after you have added your parameters to the command object.
You are using the AddWithValue method to add parameters to your command object. That is evil.
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged, MyBase.Activated
'Better to use explicit column names instead of * here, especially if you use `GetValue` with a numeric index when mapping the query results to your textboxes.
Dim str As String = "select * from customer where CustomerID=#cid"
Try
Using con As New OleDbConnection("<connection string here>"), cmd As New OleDbCommand(str, con)
con.Open()
'Assuming here that CustomerID in the customer table is of type integer
cmd.Parameters.Add("#cid", OleDbType.Integer).Value = Integer.Parse(ComboBox1.Text)
Using dr As OleDbDataReader = cmd.ExecuteReader()
If dr.Read() Then
'Instead of using magical (ordinal) numbers, it would be better to use GetOrdinal as well: dr.GetValue(dr.GetOrdinal("fieldName"))
TextBox1.Text = dr.GetValue(1)
TextBox2.Text = dr.GetValue(2)
TextBox3.Text = dr.GetValue(3)
TextBox4.Text = dr.GetValue(4)
TextBox5.Text = dr.GetValue(5)
End If
'Perhaps you also want to include an Else block (in which case the database query did not return any results) to clear the textboxes?
End Using
End Using
Catch ex As Exception
MsgBox("", ex.Message)
'Closing any ADO.NET objects will be done automatically when they are disposed (when the Using block goes out of scope).
End Try
End Sub
Obviously, I have not tested the code above, since I do not have a fitting test environment for it. Please let me know if this code causes any issues you cannot solve yourself.
You have two Sql statements in your code.
1:
str = "select * from customer where CustomerID='" & ComboBox1.Text & "'"
2:
cmd.CommandText = str = "select * from customer where CustomerID=#cid"
You should get rid of #1 - delete that line of code and change #2 to be:
cmd.CommandText = "select * from customer where CustomerID=#cid"

Database query not returning results from value

I am making a work management system and I am fairly new to Visual Basic.
What I am trying to do is retrieve the name of the employee from the database with the given ID. After that I want this name to be displayed in a Label. After that, he can press the Work Start or Work end buttons.
Here is the code:
Private Function employeeSearchwithID(PersonalNr As String) As String
Dim mitarbeiter As String
Dim r As DataRow
Access.ExecQuery("SELECT [Vorname], [Name] from [TA-Personal] WHERE ([Personal_Nr] = '" & PersonalNr & "');")
'Report and Abort on Erros or no Records found
If NoErros(True) = False Or Access.RecordCount < 1 Then Exit Function
r = Access.DBDT.Rows(0)
'Populate Label with Data
mitarbeiter = r.Item("Vorname") & " " & r.Item("Name")
Return mitarbeiter
End Function
It is used like this:
Private Sub tbxUserInput_KeyDown(sender As Object, e As KeyEventArgs) Handles tbxUserInput.KeyDown
If e.KeyCode = Keys.Enter Then 'employeeIDnumbersSelect()
Label5.Text = employeeSearchwithID(tbxUserInput.ToString)
End If
End Sub
So, the plan is to have this program running on a tablet connected to a scanner. Every employee will have a personal card. When they scan the card, I want their names to be displayed. Of course, the card will be with the ID. But I am having trouble with the names: when I give my personal number it comes up as an empty string.
I have a separate DB Module. I learned from a tutorial:
Imports System.Data.OleDb
Public Class DBControl
' DB Connection
Public DBCon As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\recycle2000.mdb;")
'DB Command
Public DBCmd As OleDbCommand
'DB Data
Public DBDA As OleDbDataAdapter
Public DBDT As DataTable
'Public Myreader As OleDbDataReader = DBCmd.ExecuteReader
'Query Paramaters
Public Params As New List(Of OleDbParameter)
' Query Stats
Public RecordCount As Integer
Public Exception As String
Public Sub ExecQuery(Query As String)
'Reset Query Stats
RecordCount = 0
Exception = ""
Try
'Open a connection
DBCon.Open()
'Create DB Command
DBCmd = New OleDbCommand(Query, DBCon)
' Load params into DB Command
Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
' Clear params list
Params.Clear()
' Execute command & fill Datatable
DBDT = New DataTable
DBDA = New OleDbDataAdapter(DBCmd)
RecordCount = DBDA.Fill(DBDT)
Catch ex As Exception
Exception = ex.Message
End Try
' Close your connection
If DBCon.State = ConnectionState.Open Then DBCon.Close()
End Sub
' Include query & command params
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New OleDbParameter(Name, Value)
Params.Add(NewParam)
End Sub
End Class
Without knowledge of the Access class, I have to recommend a different approach to querying the database. It is important to make sure that the database is not vulnerable to SQL injection, be it deliberate or accidental. The way to do that is to use what are known as SQL parameters: instead of putting the value in the query string, the value is supplied separately.
Private Function EmployeeSearchwithID(personalNr As String) As String
Dim mitarbeiter As String = String.Empty
Dim sql = "SELECT [Vorname], [Name] from [TA-Personal] WHERE [Personal_Nr] = ?;"
Using conn As New OleDbConnection("your connection string"),
cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#PersonalNr",
.OleDbType = OleDbType.VarChar,
.Size = 12,
.Value = personalNr})
conn.Open()
Dim rdr = cmd.ExecuteReader()
If rdr.Read() Then
mitarbeiter = rdr.GetString(0) & " " & rdr.GetString(1)
End If
End Using
Return mitarbeiter
End Function
Private Sub tbxUserInput_KeyDown(sender As Object, e As KeyEventArgs) Handles tbxUserInput.KeyDown
If e.KeyCode = Keys.Enter Then 'employeeIDnumbersSelect()
Dim employeeName = EmployeeSearchwithID(tbxUserInput.Text.Trim())
If String.IsNullOrEmpty(employeeName) Then
MessageBox.Show("Not found.", "Problem", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
Label5.Text = employeeName
End If
End If
End Sub
The Using command makes sure that the "unmanaged resources" involved in querying a database are cleaned up afterwards, even if something goes wrong.
You will need to change the value of OleDbType.VarChar and .Size = 12 to match the type and size of that column in the database.
The name of the parameter is only for convenience with OleDb because it is ignored in the actual query, which uses "?" as a placeholder. Please see OleDbCommand.Parameters Property for full information.
If it still does not work, then please enter the ID manually in the tbxUserInput and see if you can make it work that way.
Hang on... tbxUserInput.ToString should be tbxUserInput.Text. But everything else I wrote still applies.

a beginner in vb.net.. working on a login form

Imports MySql.Data.MySqlClient
Public Class Form1
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim con As MySqlConnection = JOKENCONN()
Public Function JOKENCONN() As MySqlConnection
Return New MySqlConnection("server=localhost; user id=root; password=; database =studentdb")
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GroupBox1.Enabled = False
End Sub
Private Sub LBLLOGIN_CLICK(sender As Object, e As EventArgs) Handles lbllogin.Click
lbllogin.Text = "Login"
lbllogin.Text = "Login"
lblname.Text = "Hi, Guest"
If lbllogin.Text = "Login" Then
GroupBox1.Enabled = True
End If
End Sub
Private Sub BTNOK_CLICK(sender As Object, e As EventArgs) Handles btnok.Click
Dim Sql As String
Dim publictable As New DataTable
Try
If txtusername.Text = "" And txtpass.Text = "" Then
MsgBox("Password or username is incorrect!")
Else
Sql = "select ' from tbluseraccount where username='" & txtusername.Text & "' and userpassword='" & txtpass.Text & "'"
With cmd
.Connection = con
End With
da.SelectCommand = cmd
da.Fill(publictable)
If publictable.Rows.Count > 0 Then
Dim user_type As String
user_type = publictable.Rows(0).Item(4)
Name = publictable.Rows(0).Item(1)
If user_type = "Admin" Then
MsgBox("Welcome " & Name & "you login as Administrator")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
ElseIf user_type = "cetakoradi2" Then
MsgBox("Welcome " & Name & "you login as cetakoradi2")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
Else
End If
Else
MsgBox("contact administrator to register")
txtusername.Text = ""
txtpass.Text = ""
End If
da.Dispose()
End If
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
End Class
this the error i received
ExecuteReader CommandText property has not been properly initialized
i really need help on that. this is the error that i receives. thank you
Assuming that the name of the field represented in publictable.Rows(0).Item(4) is named user_type, then you could use the following:
'Declare the object that will be returned from the command
Dim user_type As String
'Declare the connection object
Dim con As OleDbConnection
'Wrap code in Try/Catch
Try
'Set the connection object to a new instance
con = JOKENCONN()
'Create a new instance of the command object
Using cmd As OleDbCommand = New OleDbCommand("SELECT user_type FROM tbluseraccount WHERE username=#0 AND userpassword=#1;", con)
'Paramterize the query
cmd.Parameters.AddWithValue("#0", txtusername.Text)
cmd.Parameters.AddWithValue("#1", txtpass.Text)
'Open the connection
con.Open()
'Use ExecuteScalar to return a single value
user_type = cmd.ExecuteScalar()
'Close the connection
con.Close()
End Using
Catch ex As Exception
'Display the error
Console.WriteLine(ex.Message)
Finally
'Check if the connection object was initialized
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
con.Close()
End If
'Dispose of the connection object
con.Dispose()
End If
End Try
If (String.IsNullOrWhitespace(user_type)) Then
'Failed login
ElseIf (user_type = "Admin") Then
'Admin login
ElseIf (user_type = "cetakoradi2") Then
'cetakoradi2 login
Else
'Not a failed login, but also not an admin or cetakoradi2 either
End If
What this code does is setup a parameterized query to get just the user_type where the username and password match the parameterized values. Since there should only ever be one record that matches those conditions (presumably) then we're able to use ExecuteScalar to return just that single field value.
Just to reinforce the point, MySqlCommand.ExecuteScalar, just like the Microsoft counterparts, "executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored" and returns " The first column of the first row in the result set, or a null reference if the result set is empty ".
The proposed code by #David checks for this condition using IsNullOrWhitespace.
ExecuteScalar is effective but retrieves only one value at a time.
The other option pursued by the OP is to return a datarow, which is a valid approach if he wants to return several fields at the same time. In his example he retrieves two fields for variables user_type and Name respectively.
Be careful, VB.net like any other programming language has reserved keywords. If you do not take a habit of using good naming conventions you might one day stumble upon on one of those keywords, possibly hit obscure bugs. Name is not a good name for a variable and has the potential for confusion since every object has a name property.
To address the specific issue at hand, the error message ExecuteReader CommandText property has not been properly initialized is self-explanatory. What should have been done is simply:
With cmd
.Connection = con
.CommandText = Sql
End With
You defined a command, but did not tell it what to do. In your code variable Sql is defined but unused. With this missing bit there is a chance the code will work as expected.
Small details:
Not critical, but his condition does not work if you enter whitespace for example:
If txtusername.Text = "" And txtpass.Text = "" Then
An improvement is to simply trim the values from the textboxes:
If txtusername.Text.Trim = "" And txtpass.Text.Trim = "" Then
But I think what you want is not an And but Or. I don't think you want to allow logins without passwords.
Instead of doing multiple If/ElseIf you could have a Select Case

How do i make padleft work with the below code. I want to do search with out leading zero

With the below code I can pull info with zero in the front. I am trying to eliminate entering zero for instance 789136 for 0789136. Please advise
Private Sub BtnSearch_Click(sender As System.Object, e As System.EventArgs) Handles BtnSearch.Click
Dim connection As New SqlConnection("DATABASE CONNECTION")
Dim Table As New DataSet
Dim ZeroFill As String
If TxtBoxW1.Text = "" Then
ZeroFill = TxtBoxW1.Text.Trim
ZeroFill = ZeroFill.PadLeft(4, "0")
MsgBox(" Please Enter a valid number", MessageBoxButtons.OK)
TxtBoxW1.Focus()
connection.Open()
Else
adapter = New SqlDataAdapter("Select * From TABLENAME where COLNAME = '" & TxtBoxW1.Text.Trim & "'", connection)
Command = New SqlCommandBuilder(adapter)
ds1 = New DataSet()
adapter.Fill(ds1, "TABLENAME")
DataGridView1.DataSource = ds1.Tables("TABLENAME")
End If
connection.Close()
End Sub
your code does not make sense in many was. I'm not even sure what do you really need with those leading zeros.
1) Removing leading zeros
Dim Value As String = "0789136"
Dim ValueWithoutLeadingZeros As String = Value.TrimStart("0"c)
2) Other incinsistencies
Your if statement tests for empty string in TxtBoxW1. So there's no reason to read this
ZeroFill = TxtBoxW1.Text.Trim
ZeroFill = ZeroFill.PadLeft(4, "0")
since it will allways result in
ZeroFill = "0000"
and you're not using this value anyway.
Your connection.open and connection.close shoudl be all in the Else section, since you're not using it in if section. But this might be code cleanup consequence.
You should use parameters instead of direct query. Current version is risky for SQL Injection.
You shoudl use Using for Disposable objects.
3) Guessed version
I guess you want to trim leading zeros for validation, but pad your value with zeros for SQL search. In that case, your code should look somehow like this:
If TxtBoxW1.Text.Trim(" "c, "0"c).Length = 0 Then
MsgBox(" Please Enter a valid number", MessageBoxButtons.OK)
TxtBoxW1.Focus()
Else
Dim DS As New DataSet
Using Conn As New SqlConnection("DATABASE CONNECTION"), DA As New SqlDataAdapter("Select * From TABLENAME where COLNAME = #Param", Conn)
DA.SelectCommand.Parameters.Add(New SqlParameter("#Param", TxtBoxW1.Text.Trim.PadLeft(4, "0")))
Conn.Open()
DA.Fill(DS, "TABLENAME")
DataGridView1.DataSource = DS.Tables("TABLENAME")
End Using 'This will close the Connection for you
End If
My working code below:
Private Sub BtnSearch_Click(sender As System.Object, e As System.EventArgs) Handles BtnSearch.Click
SqlSelect = ""
sqlwhere = ""
expsql = sqlfrom & sqlwhere
Dim connection As New SqlConnection("database connection")
' Dim Command As New SqlCommand("Select * from table name where col1=#col1 = '" & TxtBoxW1.Text & "'", connection)
Dim Table As New DataSet
Dim sql As New SqlConnection
Dim ZeroFill As String
Dim ds as DataSet
connection.Open()
If TxtBoxW1.Text <> "" Then
ZeroFill = TxtBoxW1.Text.Trim
ZeroFill = ZeroFill.PadLeft(4, "0")
sqlwhere = ZeroFill
' MsgBox(" Please Enter a valid number", MessageBoxButtons.OK)
TxtBoxW1.Focus()
End If
adapter = New SqlDataAdapter("Select * From table name where col1 = " & sqlwhere & "", connection)
'adapter = New SqlDataAdapter(Sql, connection)
Command = New SqlCommandBuilder(adapter)
ds = New DataSet()
Try
adapter.Fill(ds, "Table Name")
DataGridView1.DataSource = ds1.Tables("Table Name")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
connection.Close()
End Sub