i am trying to pull the data from database to combo box , i have 2 combo box and i want to display data from different tables.
this is the code i was trying.
Try
'declare variables
Dim objDataAdapter As New SqlDataAdapter
Dim objDataAdapter1 As New SqlDataAdapter
Dim objDataSet As New DataSet()
Dim objDataSet1 As New DataSet()
'//state dataset of combo box
' Set the SelectCommand properties...
objDataAdapter.SelectCommand = New SqlCommand()
objDataAdapter.SelectCommand.Connection = sql.SqlConn
objDataAdapter.SelectCommand.CommandText = "select * from tblBrand"
objDataAdapter.SelectCommand.CommandType = CommandType.Text
'//mention the second data
objdataadapter1.SelectCommand = New SqlCommand()
objDataAdapter1.SelectCommand.Connection = sql.SqlConn
objDataAdapter1.SelectCommand.CommandText = "select * from tblModel"
objDataAdapter1.SelectCommand.CommandType = CommandType.Text
' Open the database connection...
sql.SqlConn.Open()
' Fill the DataSet object with data...
objDataAdapter.Fill(objDataSet, "tblBrand")
objDataAdapter1.Fill(objDataSet1, "tblModel")
' Close the database connection...
sql.SqlConn.Close()
With (cboxBrandName)
.DataSource = objDataSet
.ValueMember = "tblBrand.BandID"
.DisplayMember = "tblBrand.BrandName"
End With
With (cboxModel)
.DataSource = objDataSet1
.ValueMember = "tblModel.ModelID"
.DisplayMember = "tblModel.ModelName"
End With
Catch ex As Exception
End Try
End Sub
in this line not showing any error but i cannot find any result in combo box.
Here's how I do it -
Dim ds As New DataSet()
Dim conn As New SqlConnection(yourconnectionString)
Const qry As String = "SELECT * FROM tblModel"
conn.Open()
Using da As New SqlDataAdapter(qry, conn)
da.Fill(ds)
End Using
' For Combobox
With YourComboBoxName
.DisplayMember = "what you want to display to the user in combobox"
.ValueMember = "ID associated with each record"
.DataSource = ds.Tables(0)
.SelectedIndex = 0
End With
conn.Close()
Hope this helps.
Related
Before i ask "How to remove an item from a listbox populated with a database"
Is it possible to remove an item from a listbox populated with a database?
if it is possible, my code is not working:
Dim str As String
Dim drv As DataRowView = CType(ListBox1.SelectedItem, DataRowView)
str = CStr(drv.Row.Item("PName"))
ListBox1.Items.Remove(ListBox1.SelectedItem(str))
This is how i populate my lsitbox
'Populate the ListBox with personnelName from personnel '
Try
connection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Nikko Jaze Fabellon\Documents\ASRASIM.accdb")
connection.Open()
ds = New DataSet
tables = ds.Tables
dataAdapter = New OleDbDataAdapter("SELECT [FirstName],[LastName] from [Personnel] where [Status] = 'Activated' ", connection)
dataAdapter.Fill(ds, "Personnel")
Dim view1 As New DataView(tables(0))
With personnelList
.DataSource = ds.Tables("Personnel")
.DisplayMember = "FirstName"
.ValueMember = "LastName"
.SelectedIndex = 0
End With
connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
or if it is not possible, i need advice to think of another way.
i am taking the data from database and showing to combo box , i want to see the name but the original value is id.. i have one code here, please review it what i did the wrong here.
Public Sub nameshow()
Try
'declare variables
Dim objDataAdapter As New SqlDataAdapter
Dim objDataAdapter1 As New SqlDataAdapter
Dim objDataSet As New DataSet()
Dim objDataSet1 As New DataSet()
'//state dataset of combo box
' Set the SelectCommand properties...
objDataAdapter.SelectCommand = New SqlCommand()
objDataAdapter.SelectCommand.Connection = sql.SqlConn
objDataAdapter.SelectCommand.CommandText = "select * from tblBrand"
objDataAdapter.SelectCommand.CommandType = CommandType.Text
'//mention the second data
objdataadapter1.SelectCommand = New SqlCommand()
objDataAdapter1.SelectCommand.Connection = sql.SqlConn
objDataAdapter1.SelectCommand.CommandText = "select * from tblModel"
objDataAdapter1.SelectCommand.CommandType = CommandType.Text
' Open the database connection...
sql.SqlConn.Open()
' Fill the DataSet object with data...
objDataAdapter.Fill(objDataSet, "tblBrand")
objDataAdapter1.Fill(objDataSet1, "tblModel")
' Close the database connection...
sql.SqlConn.Close()
With (cboxBrandName)
.DataSource = objDataSet
.ValueMember = "tblBrand.BandID"
.DisplayMember = "tblBrand.BrandName"
End With
With (cboxModel)
.DataSource = objDataSet1
.ValueMember = "tblModel.ModelID"
.DisplayMember = "tblModel.ModelName"
End With
Catch ex As Exception
End Try
End Sub
after run the program nothing showing into the combo box. i dont understand why, and there is no error too.
i am calling this function in form load.
thanks....
Here is what I think happens after studying it a bit more:
You are getting an error. Most likely "Connection is already open." Then this error is swallowed by you try catch statement. Thus never reaching the adding of the datasource to the combobox. Try this instead:
Public Function SelectRows( _
ByVal dataSet As DataSet, ByVal connectionString As String, _
ByVal queryString As String) As DataSet
Using connection As New SqlConnection(connectionString)
Dim adapter As New SqlDataAdapter()
adapter.SelectCommand = New SqlCommand( _
queryString, connection)
adapter.Fill(dataSet)
Return dataSet
End Using
End Function
Call it with this:
objDataSet = SelectRows(objDataSet, "ConnectionString","select * from tblBrand")
With (cboxBrandName)
.DataSource = objDataSet
.ValueMember = "tblBrand.BandID"
.DisplayMember = "tblBrand.BrandName"
End With
I do believe this will work.
Is it possible to have a datagrieview populate directly from a datable ? Below is what I am trying in the form load. Basically I want it to show all the columns this query returns automatically
Dim con As New OleDbConnection
con = New OleDbConnection(connStr)
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim titleSQLStr As String = "SELECT * FROM Titles ORDER BY YearPublished DESC"
daYears = New OleDbDataAdapter(titleSQLStr, connStr)
daYears.Fill(dtYears)
cboYearsFillBy.DataSource = dtYears
cboYearsFillBy.DisplayMember = "YearPublished"
cboYearsFillBy.ValueMember = "YearPublished"
DataGridView1.AutoGenerateColumns = True
DataGridView1.DataSource = daYears
con.Close()
Change it to:
DataGridView1.DataSource = dtYears
How can I automatically refresh and view the new current datagridview after add or delete?
what code should I put after "msgbox" to view the current data?
Private Sub add()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim sSQL As String = String.Empty
Try
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "INSERT INTO course ( code, description)"
sSQL = sSQL & " VALUES (#cod, #des)"
cmd.CommandText = sSQL
cmd.Parameters.Add("#cod", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txtcode.Text)) > 0, Me.txtcode.Text, DBNull.Value)
cmd.Parameters.Add("#des", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txtdescription.Text)) > 0, Me.txtdescription.Text, DBNull.Value)
cmd.ExecuteNonQuery()
MsgBox("Data has been save.")
conn.Close()
Catch ex As Exception
MessageBox.Show("Already exist")
End Try
End Sub
You should bind your DataGridView to an appropriate DataSource, e.g. a DataTable.
Then, instead of inserting the data manually in the database, you could use a SqlDataAdapter and the DataTable your DataGridView is bound to.
Here's a simple example:
Dim cons = New SqlConnectionStringBuilder() With
{
.DataSource = "your_server",
.InitialCatalog = "your_db",
.UserID = "your_user",
.Password = "your_password"
}.ConnectionString
Dim con = New SqlConnection(cons)
con.Open()
' create a SqlDataAdapter and provide the SELECT command '
Dim adapter = New SqlDataAdapter()
Dim cb = New SqlCommandBuilder(adapter)
adapter.SelectCommand = New SqlCommand("SELECT code, description FROM course", con)
' the INSERT command can be generated '
adapter.InsertCommand = cb.GetInsertCommand()
' fill a new DataTable with data from database '
Dim dt = New DataTable()
adapter.Fill(dt)
' create a Form with DGV and Insert-Button '
Dim f = New Form()
Dim dgv = New DataGridView() With
{
.DataSource = dt,
.Dock = DockStyle.Fill
}
Dim addButton = New Button() With
{
.Text = "Add new",
.Dock = DockStyle.Bottom
}
Dim i = 0
AddHandler addButton.Click, Function(s, o)
' we insert the new data directly into the DataTable '
dt.Rows.Add(New Object() {"Some","Text"})
' and let the SqlDataAdapter handle the insert '
adapter.Update(dt)
End Function
f.Controls.Add(addButton)
f.Controls.Add(dgv)
f.ShowDialog()
Since the new data is written directly into the DataTable, the DataGridView is updated immediately.
Of course this is even easier when you use TableAdapters.
I have the following code:
Using conn = New SqlConnection(connStr)
Dim sql = "SELECT [CATEGORIA], [AREA] FROM [CATEGORIAS] WHERE ([AREA] = #AREA)"
Dim sqlCmd = New SqlCommand(sql, conn)
sqlCmd.Parameters.AddWithValue("#AREA", CStr(PublicLogin.Area))
conn.Open()
Dim ds As New DataSet
Dim da As New SqlDataAdapter(sql, conn)
da.Fill(ds, "CATEGORIAS")
With cboCat
.DataSource = ds.Tables("CATEGORIAS")
.DisplayMember = "CATEGORIAS_AREA"
.ValueMember = "CATEGORIAS_AREA"
.SelectedIndex = 0
End With
End Using
It should in theory fill the combo box right? It doesn't. It doesn't give me any errors or anything; the combo box just sits there empty. I am pretty sure the query is working well and its grabbing the correct info but the Combobox doesn't fill. If I take the where query out it fills the CB with 'System.Data.Row...'
UPDATE: Working code in case someone needs it;
Using conn = New SqlConnection(connStr)
Dim sql = "SELECT [CATEGORIA], [AREA] FROM [CATEGORIAS] WHERE ([AREA] = #AREA)"
Dim sqlCmd = New SqlCommand(sql, conn)
sqlCmd.Parameters.AddWithValue("#AREA", CStr(PublicLogin.Area))
conn.Open()
Dim ds As New DataSet
Dim da As New SqlDataAdapter(sqlCmd)
da.Fill(ds, "CATEGORIAS")
With cboCat
.DataSource = ds.Tables("CATEGORIAS")
.DisplayMember = "CATEGORIA"
.ValueMember = "CATEGORIA"
.SelectedIndex = 0
End With
End Using
Its empty because probably the query returns nothing. Notice that you are not adding the parameter to the final query on the sql variable.
You create a command with the query and the parameter but you never use it, so when you select all the values WHERE ([AREA] = #AREA) it returns nothing.
Try this:
Dim da As New SqlDataAdapter(sqlCmd)
This looks odd to me:
.DisplayMember = "CATEGORIAS_AREA"
.ValueMember = "CATEGORIAS_AREA"
It should probably be something like this:
.DisplayMember = "CATEGORIA"
.ValueMember = "AREA"
From MSDN on DisplayMember:
Gets or sets a string that specifies the property or column from which to retrieve strings for display in the combo boxes.
EDIT: You also need to replace this:
Dim da As New SqlDataAdapter(sql, conn)
with this:
Dim da As New SqlDataAdapter(sqlCmd)
Otherwise your parameters are never used.