Question Displaying SQL search results in Textbox

mcavanilla

Member
Joined
Apr 2, 2013
Messages
5
Programming Experience
Beginner
Hello,

Could someone help me to display the result of a search in textbox?


I have a table ("TBClient"), with two columns "Company" and "Name". My form has a combox to select the name of a column, and a textbox to write what i'm looking for. Below this, i have a textbox to display the result.
How can I search for a company and display the result (the name of the company), into this texbox.
I'm using VS2010, SQL server 2008 and DataSet

My code:

Private Sub btnPesquisa1_Click(sender As Object, e As System.EventArgs) Handles btnPesquisa1.Click

Dim data As SqlDataAdapter
Dim sql As String
Dim dt As New DataSet


If cmbNames.SelectedIndex = "0" Then
sql = "Select * from TBClient where Company='" & txtpesquisa1.Text & "'"
End If


data = New SqlDataAdapter(sql, cn)
data.Fill(dt, "TBCliente")
Dim dr As DataRow = dt.Tables(0).Rows(0)


DataGrid2.DataSource = dt.Tables(0)


TextBox1.Text = dr("Company").ToString


Thanks for help

Marco
 
Hi,

You have forgotten to tell us what the issue is that you are having so for starters let me start with this block of code:-

VB.NET:
If cmbNames.SelectedIndex = "0" Then
  sql = "Select * from TBClient where Company='" & txtpesquisa1.Text & "'"
End If

From your explanation there are a couple of things wrong here:-

1) First off, turn Option Strict On and leave it on forever to help you identify and correct type conversion errors as and when they occur. Once done, you will see that SelectedIndex is an Integer and not a String so this should be:-

VB.NET:
cmbNames.SelectedIndex = 0

That said, this is only ever going to work if ONLY the first item in the ComboBox is selected. What you should be testing for here is whether anything in the ComboBox is selected so you should really be saying:-

VB.NET:
If ComboBox1.SelectedIndex >= 0 Then

2) Your next issue is that you then concatenate the contents of txtpesquisa1.Text to your SQL string but you do not add the field name from the ComboBox. This should therefore be something like:-

VB.NET:
Sql = "Select * from TBClient where " & ComboBox1.Text & "='" & txtpesquisa1.Text & "'"

A couple of other points for you are:-

1) Rather than using String Concatenation to build your SQL string you should be using parameters. Have a look at this post by jmcilhinney:-

John McIlhinney's .NET Developer Blog: Using Parameters in ADO.NET

2) If you are just using one DataTable then use a DataTable and not a DataSet. There is no point in using a DataSet here.

Hope that helps.

Cheers,

Ian
 
Back
Top