How can I filter without redundant display to combobox? - vb.net

hmm this is my problem, How can I prevent double display in my Combobox if i have a datatable
"Student" with column "Section" inside is BE701P, BE101P, BE701P, BE701P, BE101P.
I want to display only to combobox the "BE701P and BE101P" like this preventing redundant display, is it possible?
Private Sub section()
Try
conn = New OleDbConnection(Get_Constring)
Dim sSQL As String = ("SELECT [section] FROM student where username like'" & Administrator.lblusername.Text & "%' ")
Dim da As New OleDbDataAdapter(sSQL, conn)
Dim ds As New DataSet
da.Fill(ds)
cmbsection.ValueMember = "section"
cmbsection.DataSource = ds.Tables(0)
cmbsection.SelectedIndex = 0
Catch ex As Exception
MsgBox("ERROR : " & ex.Message.ToString)
End Try
End Sub
it will display all data into combobox and makes redundant display. as i want to prevent redundancy. I would be very glad to any suggestions.

Why not use DISTINCT in your sql query like:
Dim sSQL As String = ("SELECT DISTINCT [section] FROM student
where username like'" & Administrator.lblusername.Text & "%' ")
See link here for mysql examples (although you did not specify your DBMS).

You can create a DataTable from the default DataView of your DataTable that show distinct records only. The advantage of using this approach is that you can keep all records in your original DataTable (which may be used for some other binding). Also note that this is a client-side operation, so you can save your server some processing effort if there are many clients doing this.
The syntax would be something like:
ds.Tables(0).DefaultView.ToTable(True, {"section"})

Related

Visual Studio Vb.net loaded dataset from oracle query missing or replacing first row of data

I have a vb.net application program that is suppose to query a oracle/labdaq database and load the dataset into a datatable. For some reason the query works fine and there is no exception thrown, however, when I load the data it seems to be missing the first row. I first noticed the issue when I did a query for a single row and it returned zero rows when I checked the datatable's row amount during debugging. I then compared all my data sets to a data miner application straight from the oracle source and i seems to always be missing one, the first, row of data when I use the application.
here is the code... I changed the query string to something else to maintain company privacy
Private Sub CaqOnSQL(strFileDirect As String)
Try
Dim connString As String = ConfigurationManager.ConnectionStrings("CA_Requisition_Attachments.Internal.ConnectionString").ConnectionString
Dim conn As New OracleConnection With {
.ConnectionString = connString
}
Dim strQuerySQL As String = "SELECT * FROM REQUISITIONS " &
"WHERE DATE BETWEEN TO_DATE('12/10/2020','MM/dd/yyyy') AND " &
"TO_DATE('12/14/2020','MM/dd/yyyy') " &
"ORDER BY ID"
conn.Open()
Dim Cmd As New OracleCommand(strQuerySQL, conn) With {
.CommandType = CommandType.Text
}
Dim dr As OracleDataReader = Cmd.ExecuteReader()
dr.read()
Dim dt As New DataTable
dt.TableName = "RESULTS"
dt.Load(dr)
ExcelFileCreation(dt, strFileDirect)
You should remove the line:
dr.read()
The call to Read is what is causing you to skip the first row, when combined with the DataTable Load method.
In addition, I have taken the liberty to make some additional changes to your code for the purposes of Good Practice. When using Database objects like Connection and Command, you should wrap them in Using blocks to ensure the resources are released as soon as possible.
Dim dt As New DataTable()
dt.TableName = "RESULTS"
Using conn As New OracleConnection(connString)
conn.Open()
Dim strQuerySQL As String = "SELECT * FROM REQUISITIONS " &
"WHERE DATE BETWEEN TO_DATE('12/10/2020','MM/dd/yyyy') AND " &
"TO_DATE('12/14/2020','MM/dd/yyyy') " &
"ORDER BY ID"
Using command = New OracleCommand(strQuerySQL , conn)
Using dataReader = command.ExecuteReader()
dt.Load(dataReader)
End Using
End Using
End Using
Note: Be wary of Using blocks when using a DataReaderas you may find the connection is closed when you don't want it to be. In this case, the DataReader is used entirely within this function and is safe to use.

how to get datatable if textbox matches your data in database

how can I possibly populate my table if like textbox.text matches from my data inside database.
I'm stuck here, not sure where I did go wrong
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim dbcommand As String
dbcommand = "SELECT * FROM aws_rdp where csn_user like " & txtCSNUser.Text & ""
adt = New OleDbDataAdapter(dbcommand, dbconn)
datatable = New DataTable
adt.Fill(datatable)
DataGridView1.DataSource = datatable
End Sub
Try putting ' before and after the quotation marks surrounding the textbox text. If you're trying to find that text within the text stored in the database you will also need wildcards (%) surrounding it too. Try:
dbcommand = "SELECT * FROM aws_rdp where csn_user like '%" & txtCSNUser.Text & "%'"
Also, as others have stated, look into using parameters in your SQL code as it will help prevent things like SQL injection and is always good practice
Found the answer to my problem by using this code. Anyways, thanks for your time replying on my query, will surely take note of your advises for my future references
Dim dbcommand As String = "SELECT * FROM aws_rdp where csn_user like '%" & txtCSNUser.Text & "%'"
Dim command As New OleDbCommand(dbcommand, dbconn)
Dim adapter As New OleDbDataAdapter(command)
Dim datatable As New DataTable
adapter.Fill(datatable)
DataGridView1.DataSource = datatable
DataGridView1.Columns(0).HeaderText = "ID"
DataGridView1.Columns(1).HeaderText = "IP Address"
DataGridView1.Columns(2).HeaderText = "Username"
DataGridView1.Columns(3).HeaderText = "Password"

Search multiple results from database and display in single textbox

guys i want to build an efficient searching tool in vb to search data from my database in mysql where i have stored paragraphs of some information. i want the search to return multiple results like google does but in a textbox in the form of 2-3 paragraphs of the same concept.Also to make the search more efficient i want to include the substring feature that is the % sign in the select query. can anyone tell me how to implement these two features ? here is my basic search code that returns just a single paragraph stored in the table into my result textbox that i hide first and then show when the results appear.
If TextBox1.Text = "" Then
MsgBox("Please Enter a Keyword")
Else
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString = "Server=localhost;UserID=root;Password=admin674;Database=db1"
Dim myadapter As New MySqlDataAdapter
conn.Open()
Dim sqlquery = "select text from text where name like '" & TextBox1.Text & "'"
Dim mycommand As New MySqlCommand
mycommand.Connection = conn
mycommand.CommandText = sqlquery
myadapter.SelectCommand = mycommand
Dim mydata As MySqlDataReader
mydata = mycommand.ExecuteReader
If mydata.HasRows = 0 Then
MsgBox("Data Not Found")
TextBox1.Clear()
TextBox2.Clear()
Else
mydata.Read()
TextBox2.Text = mydata.Item("text")
TextBox2.Show()
End If
You already answered one question yourself - how to do a substring search, simple add % to your query:
Dim sqlquery = "select text from text where name like '%" & TextBox1.Text & "%'"
(ideally, instead of supplying search value in-line you would use parametrized query, which, among other things would help avoid SQL Injection.
As for the second part - you are already using DataReader, all you have to do is instead using a single mydata.Read() command - loop thru all its results. Replace
mydata.Read()
TextBox2.Text = mydata.Item("text")
TextBox2.Show()
with
Dim sb as New StringBuilder()
While mydata.Read()
sb.AppendLine(mydata("text"))
End While
TextBox2.Text = sb.ToString()
TextBox2.Show()
This approach uses StringBuilder class which is an efficient way to concatenate multiple strings.
P.S. Don't forget to close your DataReader and Connection after use.

how to insert a row to my db table from vb.net

am using vb.net, and i want to insert a row to my db Table "adwPays" from my windows form.
this is my code:
Dim CC, EngName, FreName, LanCode As String
Dim DialCode As Integer
CC = txtCC.Text
EngName = txtEN.Text
FreName = txtFN.Text
LanCode = txtLC.Text
DialCode = txtDC.Text
Dim MyConn As New SqlConnection("Server=(local);Database=dbAjout;Integrated Security=True")
Dim query As String
query = "INSERT INTO adwPays (CC, Anglais,Francais,CodeLangue,IndicInter) VALUES ( ' " & CC & "','" & EngName & "','" & FreName & "','" & LanCode & "','" & DialCode & " ');"
Dim cmd As New SqlCommand(query, MyConn)
MyConn.Open()
cmd.ExecuteScalar()
MyConn.Close()
BUT its giving me this error
"An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: String or binary data would be truncated.
The statement has been terminated."
any help?
Use a parameterized query like this
Dim query = "INSERT INTO adwPays (CC, Anglais,Francais,CodeLangue,IndicInter) " &
"VALUES (#cc, #ename, #fname, #lan, #dial)"
Using MyConn = New SqlConnection("Server=(local);Database=dbAjout;Integrated Security=True")
Using cmd = New SqlCommand(query, MyConn)
cmd.Parameters.AddWithValue("#cc", CC)
cmd.Parameters.AddWithValue("#ename", EngName)
cmd.Parameters.AddWithValue("#fname", FreName)
cmd.Parameters.AddWithValue("#lan", LanCode)
cmd.Parameters.AddWithValue("#dial", DialCode)
MyConn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Using a parameterized query allows to avoid problems with Sql Injections and clears the command text from the formatting quotes around strings and dates and also let the framework code pass the correct decimal point for the numeric types when need
I have also added a Using Statement around the SqlConnection and the SqlCommand to be sure that the objects are closed and destroyed. The parameters are all passed as strings, this could be wrong if any of your database fields are not of text type.
It sounds like you have a String value that is longer than the database type size allows. Can you verify the type and size of each of the following fields:
cc
ename
fname
lan
Now cross-reference those sizes with what the values are in the textbox fields you are pulling them from in the UI.
My money is on one of those exceeding the database size limits.
If that is the case, then you need to introduce length checking before you attempt to save to the database.

How to create a ComboBox autofill using SQLite Data Reader

I have two Combo-Boxes like this
I need to create an auto-fill feature for the 1st Combo-Box. It should list the EmployeeID if Search-By Field is specified as Employee-Number. Similarly it should list Employee First Name along with Last Name if the Search-By Field is Employee-Name.
How can I do this? I have no clue, I am doing this for the first time. I am using SQLite, Visual Studio 2010.
Dim mySelectQuery As String = "SELECT " & Search & " FROM EmployeeTable WHERE Status LIKE '" & Status & "'"
Dim myConnString As String = "Data Source=" & Application.StartupPath & "\Database\SimpleDB.db3"
Dim sqConnection As New SQLiteConnection(myConnString)
Dim sqCommand As New SQLiteCommand(mySelectQuery, sqConnection)
sqConnection.Open()
Try
' Always call Read before accessing data.
Dim sqReader As SQLiteDataReader = sqCommand.ExecuteReader()
Dim j As Integer = sqReader.FieldCount
While sqReader.Read()
'''''''''''''''''''''''Here, Don't know how to list the items from the query reult into the combo-box
End While
'Close Reader after use
sqReader.Close()
Catch ex As Exception
'Show Message on Error
MsgBox(ex.ToString)
Finally
'At Last Close the Connection
sqConnection.Close()
End Try
I'm not sure entirely what you are asking but I think this is it.
In the SelectedIndex changed event you would have something similar to the code below. You can add an If statement to check what you are querying for and adjust your query accordingly.
Dim dt as New DataTable
Try
Using sqlConn
sqlConn.Open()
Using cmd As New SqlCommand("your query")
cmd.Connection = sqlConn
cmd.CommandType = CommandType.Text
Dim reader as SqlDataReader = cmd.ExecuteReader()
dt.Load(reader)
End Using
End Using
Catch ex As SqlException
Throw New Exception(ex.Message)
End Try
With yourComboBox
.DataSource = dt
.DataValueField = "columName you want to be the value of the item"
.DataTextField = "columnName of the text you want displayed"
End With
Notice the following properties for the combo-box: AutoCompleteMode, AutoCompleteSource, AutoCompleteCustomSource.
Select the appropriate AutoCompleteMode. See details on the different modes at this link.
For AutoCompleteSource, choose either ListItems (in which case the source will be the items of the ComboBox) or CustomSource. Should you choose CustomSource, set the appropriate source as the value of the ComboBox's AutoCompleteCustomSource property.
This should provide you with enough details to do what you're looking for.
The other requirements you've listed - such as taking the data from an SQLite database or changing between employee name and employee number - won't affect the way you work with the AutoComplete feature.