How to loop through MS Access table-column values pulled in a Combo box (VB .Net) - vb.net

This is in continuation of a previously resolved query related to Access Database values in Combo box.
The code below is working fine. i.e. it gets the data from an Access table column into the dropdown of a combo-box. What I want is how to assign those values against the Combobox.SelectedIndex? I added TagComboBox1.SelectedIndex = 0 but I want something that will automatically assign Index to the values populated in the combo-box dropdown.
The source table is tag_data '
Key Column is tag_unique_id
I need it as I want to use the combobox.selectedindexchanged event to carry out further tasks. I played around but did not succeed.
Dim dt As New DataTable
Dim query As String = "select tag_unique_id from tag_data order by tag_unique_id"
Using connection As New OleDbConnection(strConnectionString)
Using command As New OleDbCommand(query, connection)
Using adapter As New OleDbDataAdapter(command)
connection.Open()
adapter.Fill(dt)
connection.Close()
End Using
End Using
End Using
If dt.Rows.Count > 0 Then
TagComboBox1.DataSource = dt
TagComboBox1.ValueMember = "tag_unique_id"
TagComboBox1.DisplayMember = "tag_unique_id"
TagComboBox1.SelectedIndex = 0
End If
UPDATE: Below is the combobox.selectedindexchanged code. The index can be anything during working of project and hence instead of specifying as selectedindex=0 (1,2,3..) can I have a variable which will assign a new value to selectedindexchanged event?
Private Sub TagComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As system.EventArgs) Handles TagComboBox1.SelectedIndexChanged
'reference http://stackoverflow.com/questions/13152534/view-data-from-database-using-textbox
Dim dt As New DataTable
Dim query As String = "select tag_text from tag_data"
Dim dr As OleDbDataReader
Dim connection As New OleDbConnection(strConnectionString)
Dim command As New OleDbCommand(query, connection)
connection.Open()
If TagComboBox1.SelectedIndex = 0 Then
dr = command.ExecuteReader
While dr.Read()
TagTextBox.Text = dr("tag_text").ToString
End While
dr.Close()
End If

If you are trying to populate a textbox according to the selected index of the combobox this is what you need to do.
For index As Integer = 0 To (ComboBox1.Items.Count - 1)
textbox.Text = ComboBox1.Items(index)
Next

Related

Compare db value with textbox value VB

My Table
I load the windows user name to textbox1.text using 'System.Environment'
After that I query this and compare the textbox value to the PersonName in db
if it matches, I want to get the relevant Department name ie if it's 'manager'
then I want to display a form from menuitem_click event. My code is below
it dosent work can some one please help with this.
Private Sub MySamplesToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles MySamplesToolStripMenuItem.Click
Dim cn As New SqlClient.SqlConnection("Data Source=ffff;Initial Catalog=ffff;User ID=****;Password=****;")
Dim cmd As New SqlClient.SqlCommand
Dim tbl As New DataTable
Dim da As New SqlClient.SqlDataAdapter
Dim reader As SqlClient.SqlDataReader
Dim ta As String
Try
cn.Open()
Dim sql As String
sql = "select * from dbo.Person where [PersonName] ='" + TextBox1.Text + "'"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
While reader.Read
ta = reader.Item("Department")
If ta = 'Maneger' Then
Form2.Show()
End If
' TextBox2.Text = reader.Item("Department")
'TextBox2.Text = reader.Item("dob")
End While
cn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
No matter how you spell it, Manager or Maneger, just make sure what is in the database matches what is in your If statement. I think I would use a drop down box for you to select the Department wherever you are inserting the Person so the Department name would match.
The Using...End Using blocks ensure that you database objects are closed and disposed even if there is an error.
You can pass your Sql statement and the connection directly to the constructor of the command. If all you need is the Department then don't drag down all the date with "*".
Never concatenate strings to build Sql statements. A hacker could type in TextBox1 "Joe; Drop Table dbo.Person;" Using parameters stops this hole because the .Value of the parameter is treated as only a value not executable code.
You are only expecting one value in return so you can use .ExecuteScalar which returns the first column of the first row in the result set.
Your code is very fragile because I suspect you could have duplicate names unless you require unique user names.
Private Sub MySamplesToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles MySamplesToolStripMenuItem.Click
Try
Using cn As New SqlClient.SqlConnection("Data Source=ffff;Initial Catalog=ffff;User ID=****;Password=****;")
Using cmd As New SqlClient.SqlCommand("Select Department From dbo.Person Where PersonName = #Name;", cn)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = TextBox1.Text
cn.Open()
Dim ta As String = cmd.ExecuteScalar.ToString
If ta = "Maneger" Then
Form2.Show()
End If
TextBox2.Text = ta
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

VB Dot Net Binding records to a listview base on the first letter

Please i want to select list of products base on the first letter by keypress in a textbox.
This is how i load records to the listview from the database.
Try
cmd.CommandText = ("Select ProductCode From STOCK_DETAILS")
cmd.Connection = net_55
Dim Da As New OleDbDataAdapter(cmd)
Dim Ds As New DataSet
Da.Fill(Ds, "STOCK_DETAILS")
Dim Bs As New BindingSource
Bs.DataSource = Ds
Bs.DataMember = "STOCK_DETAILS"
With ProductListView
For i As Integer = 0 To Bs.Count - 1
Dim lst As New ListViewItem
With lst
.Text = Bs.Current("ProductCode").ToString
'.SubItems.Add(Bs.Current("CompanyName").ToString)
End With
.Items.Add(lst)
Bs.MoveNext()
Next
End With
The above code here will bind all the records in that column to the listview.
But this is not what i want to achieve.
For example the select statement here in SQL helps me achieve my goal at the back end. This same code is not working at the VB side.
Select ProductCode From STOCK_DETAILS
Where ProductCode Like 'H%'
Any help would grateful.
If it was acceptable to perform the filter at the SQL level, you could try passing the first letter of the TextBox into the SQL string. Something like this:
Dim commandText As String = String.Format("SELECT ProductCode FROM STOCK_DETAILS WHERE ProductCode LIKE '{0}%'", textBoxValue)
cmd.CommandText = (commandText)
cmd.Connection = net_55
Dim Da As New OleDbDataAdapter(cmd)
Dim Ds As New DataSet
Da.Fill(Ds, "STOCK_DETAILS")
Dim Bs As New BindingSource
Bs.DataSource = Ds
Bs.DataMember = "STOCK_DETAILS"
The above code could be called from a text changed event in the TextBox.
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If TextBox1.Text.Length > 0 Then
Call GetData(TextBox1.Text.Substring(0, 1))
End If
End Sub

How to get associated column's value from selected item of combo-box in visual basic 2013?

I am working with Visual Basic 2013 and sqlite. My table structure is like -
topic_id
topic_name
subject_id
subject_name
chapter_no
I am importing this table into combo box as -
Dim con As SQLiteConnection
Dim sql As String
Dim da As SQLiteDataAdapter
Dim ds As New DataSet
Dim cmd As New SQLiteCommand
con = New SQLiteConnection("Data Source = test.db;Version=3;")
con.Open()
sql = "SELECT * FROM med_topics"
da = New SQLiteDataAdapter(sql, con)
da.Fill(ds, "TopicsList")
con.close()
cboTopicsList.DisplayMember = "Topic_Name"
cboTopicsList.ValueMember = "Topic_Id"
cboTopicsList.DataSource = ds.Tables("TopicsList")
I want to use tables other column's value (but don't want them to display in combo box) viz. "subject_id, subject_name, chapter_no".
I know these values are imported in TopicsList, but I don't know, how to get the corresponding value of the selected item. I am stuck here.
A ComboBox populate its object collection (the Items property) with DataRowView objects when bound to a DataTable. This is because the DataTable class implements IListSource which the ComboBox looks for. It returns a DataView, the DefaultView of the table.
Private Sub cboTopicsList_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboTopicsList.SelectedIndexChanged
Dim rowView As DataRowView = TryCast(cboTopicsList.SelectedItem, DataRowView)
If (Not rowView Is Nothing) Then
Dim row As DataRow = rowView.Row
Dim subjectName As String = DirectCast(row.Item("subject_name"), String)
'...
End If
End Sub

Database not updating new row

Insert new row inside DataGridView
This answer makes it seem like the database should update with the rows.add
Some other sites have instructions, but form a perspective of creating the database from scratch. I already have a database and just want the stupid thing to accept new data.
Here's what I have done:
Private Sub InitializeDataGridView()
Try
' Set up the DataGridView.
With Me.DataGridView1
' Automatically generate the DataGridView columns.
.AutoGenerateColumns = True
' Set up the data source.
'bindingSource1.DataSource = GetData("SELECT * FROM Places and Stuff")
MyTable = GetData("SELECT * FROM Places and Stuff")
'MyDataSet = bindingSource1.DataSource
'MyTable = MyDataSet.Tables(0)
.DataSource = MyTable
' Automatically resize the visible rows.
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders
' Set the DataGridView control's border.
.BorderStyle = BorderStyle.Fixed3D
' Put the cells in edit mode when user enters them.
.EditMode = DataGridViewEditMode.EditOnEnter
' Disables Add New Row
.AllowUserToAddRows = False
End With
Catch ex As SqlException
MessageBox.Show(ex.ToString, _
"ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
System.Threading.Thread.CurrentThread.Abort()
End Try
End Sub
I am binding the DGV to a table. It seems like maybe I need a dataset somewhere to update but I cannot figure out how to populate a dataset with a table that is also a sql database. You can also see where I have played around with other datasets/datatables etc.
I also got my datagridview to add a row but the database is being lazy:
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
'Determine Last Row Index
Dim dgvrowCnt As Integer = DataGridView1.Rows.Count - 1
If DataGridView1.Rows.Count > 0 Then
Dim myRow As DataRow = MyTable.NewRow
myRow(0) = DataGridView1.Rows(dgvrowCnt).Cells(0).Value + 1
MyTable.Rows.Add(myRow)
Else
Dim myRow As DataRow = MyTable.NewRow
myRow(0) = 230
MyTable.Rows.Add(myRow)
End If
End Sub
I am a little saddened by not being able to use myRow("<column name here>") = 230 but I'll have to get over it I guess.
I have tried refreshing and checking the table to see if my form needs to be refreshed, but that doesn't seem to be the case.
This page http://support.microsoft.com/kb/301248 has 2 lines and claims it does what I am hoping for:
Dim objCommandBuilder As New SwlCammandBuilder(daAuthors)
daAuthors.Update(dsPubs, "Authors")
I cannot get my table into a dataset as shown in the binding lines of my example.
It seems that you haven't understood a fundamental concept of ADO.NET. The DataTable and other objects like the DataSet are 'disconnected' objects, meaning that adding/updating and removing rows doesn't update/insert/delete the database table.
You need to create an SqlCommand, prepare its command text and then Execute a query to update your db (other methods include using an SqlDataAdapter and its Update method)
For example, to insert a single row in a datatable your code should be something like this
Using con = New SqlConnection(.....constringhere...)
Using cmd = new SqlCommand("INSERT INTO table1 (field1) values (#valueForField)", con)
con.Open()
cmd.Parameters.AddWithValue("#valueForField", newValue)
cmd.ExecuteNonQuery()
End Using
End Using
A more complete tutorial could be found here
Instead this could be a pseudocode to use a SqlDataAdapter and a SqlCommandBuilder to automate the construction of the commands required to store your changes back to the database
' Keep the dataset and the adapter at the global class level'
Dim da As SqlDataAdapter = Nothing
Dim ds As DataSet
Private Function GetData(ByVal sqlCommand As String) As DataSet
ds As New DataSet()
Dim connectionString As String = "Data Source=...."
Using con = New SqlConnection(connectionString)
conn.Open()
Using command = New SqlCommand(sqlCommand, con)
Using da = New SqlDataAdapter(command)
da.Fill(ds)
End Using
End Using
End Using
Return ds
End Function
Use the first table inside the DataSet returned by GetData as Datasource of the grid (or just use the whole dataset)
.DataSource = GetData(.......).Tables(0)
' Add a new button to submit changes back to the database'
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim builder = New SqlCommandBuilder(da)
da.UpdateCommand = builder.GetUpdateCommand()
da.InsertCommand = builder.GetInsertCommand()
da.DeleteCommand = builder.GetDeleteCommand()
da.Update(ds)
End Sub
Please, note that I cannot test this code, and I offer it as a pseudocode without any error checking required by a more robust application.

VB.NET: Clear DataGridView

I've tried -
DataGridView1.DataSource=Nothing
and
DataGridView1.DataSource=Nothing
DataGridView1.Refresh()
and
DataGridView1.RefreshEdit()
None of them works..
I've written a method that sets the DataSource of the DataGridView when executed. but each time i execute it, it replicates the data with new value and appends it to the previous contents of the DGV.. I wanna clear the content and then add the values.. Is that possible?
If the DataGridView is bound to any datasource, you'll have to set the DataGridView's DataSource property to Nothing.
If the DataGridView is not bound to any data source, this code will do the trick:
DataGridView.Rows.Clear()
For unbound cases note that:
DataGridView.Rows.Clear()
leaves the Columns collection in place.
DataGridView.Columns.Clear()
..will remove all the columns and rows. If you are using the DGV unbound, and on next use the columns change, clearing the Rows may not be adequate. For library code clear all the columns before adding columns.
I'd probably use this...
DataGridView1.Rows.Clear()
to clear out the rows and then rebind.
Follow the easy way like this
assume that ta is a DataTable
ta.clear()
DataGridView1.DataSource = ta
DataGridView1.DataSource = Nothing
Can you not bind the datagridview to an empty collection (instead of null). That do the trick?
To remove the old record in datagridview when you are searching for new result,with button_click event write the following code,
me.DataGridview1.DataSource.clear()
this code will help to remove the old record in datagridview.
I found that setting the datasource to null removes the columns. This is what works for me:
c#:
((DataTable)myDataGrid.DataSource).Rows.Clear();
VB:
Call CType(myDataGrid.DataSource, DataTable).Rows.Clear()
My DataGridView is also bound to a DataSource and myDataGridView.Columns.Clear() worked fine but myDataGridView.Rows.Clear() did NOT. Just an FYI for those who have tried .Rows.
Don't do anything on DataGridView, just clear the data source. I tried clearing myDataset.clear() method, then it worked.
I've got this code working in a windows form,
Public Class Form1
Private dataStuff As List(Of String)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
DataGridView1.DataSource = Nothing
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dataStuff = New List(Of String)
dataStuff.Add("qwerty")
dataStuff.Add("another")
dataStuff.Add("...and another")
DataGridView1.DataSource = dataStuff
End Sub
End Class
You should remove the table from dataset if the datagrid is bind to some datatable. Your Gridview will be cleared automatically. No other way.
[YourDatasetName].Tables.Clear()
I had the same problem on gridview content clearing. The datasource i used was a datatable having no columns, and i added columns and rows programmatically to datatable. Then bind to datagridview. I tried the code related with gridview like gridView.Rows.Clear(), gridView.DataSource = Nothing
but it didn't work for me. Then try the below code related with datatable before binding it to datagridview each time.
dtStore.Rows.Clear()
dtStore.Columns.Clear()
gridView.DataSource = dtStore
And is working fine, no replication in DataGridView
1) create button named it Clear.Inside insert tfhe following code
datagridviewer.DataSource=nothing
2) In your search button begin your code by the following statement
datagridviewer.DataSource = DataSet.table
Nb:instead of table put the real name of your table
ex: datagridviewer.DataSource = DataSet.client
When feeding info from an SQL query into a datagridview you can clear the datagridview first before reloading it.
Where I have defined dbDataSet as New DataTable I can do a clear.
dbDataSet must be at the start of the form within the Public Class Form
Dim dbDataset AS New DataTable
within the code of you Private Sub, place
dbDataSet.Clear()
You may have a user scenario such that you want to keep the data binding and only temporarily clear the DataGridView. For instance, you have the user click on a facility on a map to show its attributes for editing. He is clicking for the first time, or he has already clicked on one and edited it. When the user clicks the "Select Facility" button, you would like to clear the DataGridView of the data from the previous facility (and not throw an error if it's his first selection). In this scenario, you can achieve the clean DataGridView by adapting the generated code that fills the DataGridView. Suppose the generated code looks like this:
Try
Me.Fh_maintTableAdapter.FillByHydrantNumber(Me.Fh2010DataSet.fh_maint, hydrantNum)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
We are filling the DataGridView based on the hydrant number. Copy this code to the point where you want to clear the DataGridView and substitute a value for "hydrantNum" that you know will retrieve no data. The grid will clear. And when the user actually selects a facility (in this case, a hydrant), the binding is in place to fill the DataGridView appropriately.
If the DataGridView is bound to any datasource,
DataGridView1.DataSource = Nothing
DataGridView1.DataBind()
Dim DS As New DataSet
DS.Clear() - DATASET clear works better than DataGridView.Rows.Clear() for me :
Public Sub doQuery(sql As String)
Try
DS.Clear() '<-- here
' - CONNECT -
DBCon.Open()
' Cmd gets SQL Query
Cmd = New OleDbCommand(sql, DBCon)
DA = New OleDbDataAdapter(Cmd)
DA.Fill(DS)
' - DISCONNECT -
DBCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
If the GridView (Say the name is gvArchive) is bound to any DataSource, the following will clear it:
gvArchive.DataSource = Nothing
gvArchive.DataBind()
just write this
DataGridView1.DataSource = ""
I had the same problem: I was programmatically binding my GridView1 to one SQL table [dictonary] or another [meny] BUT when I selected the second table from my RadioButtonList1, I was getting an error (System.Web.HttpException: Field or property with the title [the first column's title from the previously selected table] was not found in the selected data source.) i.e. saying that the columns from my first-selected table couldn't be found. All I needed to do was insert:
GridView1.Columns.Clear()
before adding the table columns. Here goes the full code:
Dim connectionString As String = "your-string-details"
Dim connection As New SqlConnection(connectionString)
Then comes your first Sub:
Private Sub BindOrders()
connection.Open()
Dim sqlCommand As String = "SELECT * FROM [dictionary]"
Dim dataAdapter As New SqlDataAdapter(sqlCommand, connection)
Dim dt As New DataTable()
dataAdapter.Fill(dt)
GridView1.Columns.Clear() ' clear columns before adding new ones
If GridView1.Columns.Count <= 0 Then
Dim Field As New BoundField()
Field.DataField = "id"
Field.HeaderText = "id"
GridView1.Columns.Add(Field)
Field = New BoundField()
Field.DataField = "strArHundreds"
Field.HeaderText = "strArHundreds"
GridView1.Columns.Add(Field)
Field = New BoundField()
Field.DataField = "strArTens"
Field.HeaderText = "strArTens"
GridView1.Columns.Add(Field)
Field = New BoundField()
Field.DataField = "strArSingles"
Field.HeaderText = "strArSingles"
GridView1.Columns.Add(Field)
End If
GridView1.DataSource = dt
GridView1.DataBind()
connection.Close()
End Sub
Then comes your second Sub:
Private Sub BindDocuments()
connection.Open()
Dim sqlCommand As String = "SELECT * FROM [meny]"
Dim dataAdapter As New SqlDataAdapter(sqlCommand, connection)
Dim dt As New DataTable()
dataAdapter.Fill(dt)
GridView1.Columns.Clear() ' clear columns before adding new ones
If GridView1.Columns.Count <= 0 Then
Dim Field As New BoundField
Field = New BoundField
Field.DataField = "id"
Field.HeaderText = "id"
GridView1.Columns.Add(Field)
Field = New BoundField
Field.DataField = "nazev"
Field.HeaderText = "nazev"
GridView1.Columns.Add(Field)
End If
GridView1.DataSource = dt
GridView1.DataBind()
connection.Close()
End Sub
Finally comes your RadioButton:
Protected Sub RadioButtonList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RadioButtonList1.SelectedIndexChanged
Dim index As Integer
index = RadioButtonList1.SelectedIndex
Select Case index
Case 0
BindOrders()
Exit Select
Case 1
BindDocuments()
Exit Select
End Select
End Sub
For completion, here is the code for the GridView1 and the RadioButtonList1 in the associated aspx.file:
<asp:RadioButtonList ID="RadioButtonList1"
runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
<asp:ListItem>Obraty</asp:ListItem>
<asp:ListItem>Dokumenty</asp:ListItem>
</asp:RadioButtonList>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
</asp:GridView>
This all works well now.
The mistake that you are making is that you seem to be using a dataset object for storing your data. Each time you use the following code to put data into your dataset you add data to the data already in your dataset.
myDataAdapter.Fill(myDataSet)
If you assign the table in your dataset to a DataGridView object in your program by the following code you will get duplicate results because you have not cleared data which is already residing in your dataset and in your dataset table.
myDataGridView.DataSource = myDataSet.Tables(0)
To avoid replicating the data you have to call clear method on your dataset object.
myDataSet.clear()
An then assign the table in your dataset to your DataGridView object.
The code is like this.
myDataSet.clear()
myDataAdapter.Fill(myDataSet)
myDataGridView.DataSource = myDataSet.Tables(0)
You can try this code:
' clear previous data
DataGridView2.DataSource = Nothing
DataGridView2.DataMember = Nothing
DataGridView2.Refresh()
Try
connection.Open()
adapter1 = New SqlDataAdapter(sql, connection)
' clear data already in the dataset
ds1.Clear()
adapter1.Fill(ds1)
DataGridView2.DataSource = ds1.Tables(0)
connection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Use this code where ever you want to implement clear datagridview command
datagridview1.datasource= nothing
datagridview1.datasource= ds
dt.clear() 'Dt as new DATATABLE
ds.clear() 'Ds as new Dataset
this code will clear the datagridview and wil stop data duplication when populating data from database.
You can do in this way:
DataGridView1.Enable = false
DataGridView1.DataSource = Nothing
DataGridView1.Enable = true
For the Clear of Grid View Data You Have to clear the dataset or Datatable
I use this Code I clear the Grid View Data even if re submit again and again it will work
Example
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dar As OleDbDataReader
Dim dt As New DataTable
If (con.State <> 1) Then
con.Open()
End If
dt.Clear() 'To clear Data Every time to fresh data
cmd.Connection = con
cmd.CommandText = "select * from users"
da.SelectCommand = cmd
da.Fill(dt)
DataGridView1.DataSource = dt
DataGridView1.Visible = True
cmd.Dispose()
con.Close()
You can do that only by the following 2 lines:
DataGridView1.DataSource=Nothing
DataGridView1.DataBind()
You can also try this code if you want to clear all data in your DataGridView
DataGridView1.DataSource.Clear()
Try this for a specific cell:
Datagrid.Rows(RowIndex).Cells(ColIndex).Value = DBNull.Value
DgRemolques is the name of my Data grid on WPF
dgRemolques.ItemsSource = Nothing
but i need to clean also de DataTable
dtRemolques.Clear()