I have a datagridview with datasource an Acces table.
The datagridview is filled and perfect but now I want to create an extra Combobox with a filter possibility.
This is in my load function of the page:
Private Sub ArchiefFacturatie_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'CharelIjsDataSet.tblFactuur' table. You can move, or remove it, as needed.
Me.TblFactuurTableAdapter.Fill(Me.CharelIjsDataSet.tblFactuur)
'Filling comboxbox part skipped
End Sub
At this moment the combobox is filled an the datagridview also.
Now I created an on selectChange action on the combobox.
I had no idea how to tackle this but I've tried it:
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
'Ophalen id artikel
Dim klantid As Integer
klantid = ComboBox1.SelectedValue
Dim klantidstr As String
klantidstr = klantid.ToString
'Via query overige gegevens ophalen
' OLEDB select query
Dim myConnection As OleDbConnection
Dim DBpath As String = "C:\Facturatie\CharelIjs.accdb"
Dim sConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBpath & ";Persist Security Info=True"
myConnection = New OleDbConnection(sConnectionString)
myConnection.Open()
Dim SQLstr As String
SQLstr = "SELECT * FROM tblKlant WHERE KlantID = #id"
Dim cmd As New OleDbCommand(SQLstr, myConnection)
Dim da As New OleDbDataAdapter(cmd)
Dim ds As New DataSet()
cmd.Parameters.Add("#id", OleDbType.VarChar)
cmd.Parameters(0).Value = klantid
Try
da.Fill(ds, "tblKlant")
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Can't load Web page" & vbCrLf & ex.Message)
Return
End Try
DataGridView1.DataSource = ds.Tables("tblKlant")
End Sub
You can get rid of all that code in SelectionChangeCommitted event handler for a start. You have a typed DataSet so use it. Open the DataSet designer by double-clicking the DataSet in the Solution Explorer. You should have a TblKlantTableAdapter adapter. Right-click it and add a new query. Add your filtered query and name the methods FillByKlantID and GetDataByKlantID.
Back in your form designer, add an instance of your table adapter and a BindingSource. Bind the BindingSource to tblKlant in your DataSet and bind your grid to the BindingSource. Now, when the user makes a selection, you first clear the table in the DataSet, then you get the ID from the ComboBox and pass it to a call to that FillByKlantID method. That will get the filtered data from the database and populate the DataTable. Because the DataTable is bound to the BindingSource and that's bound to the grid, the data will be displayed.
Related
This has got to be close, but it's been a long day and I'm tired now so I can;t really see what the problem is. Basically, I have a table in SQL Server with 2 columns; one has the names of reports and the other has some SQL Scripts that I want to pass into a GridView, based on what a user selects from a ListBox. Here is my code.
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim sqlConn As New SqlClient.SqlConnection("Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True")
sqlConn.Open()
Dim cmd As New SqlClient.SqlCommand("Select ReportName From [Table_1] order by ReportName", sqlConn)
Dim dsColumns As New DataSet
Dim daAdapter As New SqlClient.SqlDataAdapter(cmd)
daAdapter.Fill(dsColumns)
If dsColumns.Tables(0).Rows.Count > 0 Then
ListBox1.Items.Clear()
For i As Integer = 0 To dsColumns.Tables(0).Rows.Count - 1
ListBox1.Items.Add(dsColumns.Tables(0).Rows(i)(0).ToString())
Next
End If
Catch ex As Exception
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connetionString As String
Dim SqlStr As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim ds As New DataSet
Dim myItem As String
connetionString = "Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True"
connection = New SqlConnection(connetionString)
'Dim iIndex As Integer = ListBox1.SelectedIndex
myItem = ListBox1.SelectedItem
SqlStr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
connection.Open()
adapter = New SqlDataAdapter(SqlStr, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
I guess the problem is passing the SQL to the GridView. When I select the first Item, I see this in my GridView.
SELECT [OrderID]
,[CustomerID]
,[EmployeeID]
,[OrderDate]
,[RequiredDate]
,[ShippedDate]
,[ShipVia]
,[Freight]
,[ShipName]
,[ShipAddress]
,[ShipCity]
,[ShipRegion]
,[ShipPostalCode]
,[ShipCountry]
FROM [Test].[dbo].[Orders]
That's pretty close, but I want to get that SQL fed into the GridView, and get the results of the SQL displayed in the GridView, not eh SQL statement itself.
This is what I see now.
I want to see something more like this.
Finally, I am curious to know of the GridView can be made dynamic, so if I stretch out the window the GridView shows more columns. Now, if I stretch out the form window, the GridView stays static.
You need to actually run the retrieved Sql statement:
sqlstr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
connection.Open()
Dim cmd As New SqlCommand(sqlstr, connection)
Dim sqlstr_report As String = CStr(cmd.ExecuteScalar())
cmd.Dispose()
adapter = New SqlDataAdapter(sqlstr_report, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.DataSource = ds.Tables(0)
Use the .Anchor property of the DataGridView to make it resize with the form
So I've been doing this personal project for myself where I'm trying to create a program where the user (me in this case) can add, delete, update a database via a form where I can fill out the necessary information.
To give a general idea, the main form has a data grid view where if I click load, the database appears wit the records. I got all of that set. However where I am having trouble is in Form1 which is the adding a record form where I write down the information and after filling it out I press the "commit" button so that it can write it on the MS Access Database. This is a general view of the code I have inside commit button. Just for reference, Profiles is the name of the mdb file and Contacts is the name of the table containing the recods.
Imports System.Data.OleDb
Private Sub btnCommit_Click(sender As Object, e As EventArgs) Handles btnCommit.Click
If inc <> 0 Then
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim dsnewrow As DataRow
dsnewrow = ds.Tables("Profiles").NewRow()
dsnewrow.Item("First_Name") = FirstNameText.Text
dsnewrow.Item("Last_Name") = LastNameText.Text
ds.Tables("Profiles").Rows.Add(dsnewrow)
da.Update(ds, "Profiles")
Main.DataGridView1.Refresh()
MsgBox("New Record added")
End If
End Sub
What I don't know is if it's necessary to add this following code to Form1_load:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source= path to the mdb file"
con.ConnectionString = dbProvider & dbSource
con.Open()
Sql = "SELECT * FROM Contacts"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Profiles")
con.Close()
Maxrows = ds.Tables("Profiles").Rows.Count
inc = -1
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
the following are declared, just for reference:
Dim con As New OleDb.OleDbConnection
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
Dim dbProvider, dbSource As String
Dim sql As String
Dim Maxrows As Integer
Syntax error in INSERT INTO statement on this line:da.Update(ds, "Profiles")
Any help would be greatly appreciated, been at it for days unfortunately :/
Let me know if you need any additional information to clarify.
Try this. In your btnCommit_Click method after
Dim cb As New OleDb.OleDbCommandBuilder(da)
add the following:
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
Does that help?
I am using VB.NET to pull some data from an SQL database into a Datagridview.
I then want the user to be able to modify the information and save it back to the database, which I have working fine.
What I need to be able to do now is to restrict the values, but way of a combobox for the field Tarrif.
I have configured a DataSource called Tarrif1 and I am using the below code.
I have a couple of issues/questions.
Firstly the dropdown shows a single value of "System.Data.DataViewManagerListItemTypeDescriptor" not the Tarrif1 values.
Secondly, I now have 2 columns on my datatable called Tarrif, the original database one and the one I have added - How can I get the ComboBox to right back to the appropriate Tarrif database field.
Here is my code:
Imports System.Data.SqlClient
Imports System.Data.Common
Public Class ViewCustomersForm
Dim ds As DataSet = New DataSet()
Dim connStr As String = "server=barry-laptop\SQLEXPRESS; database=BillingReferenceData; integrated security=yes"
Dim sql As String = "SELECT * FROM Customers"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim comm As SqlCommand = New SqlCommand(Sql, conn)
Dim dataadapter As SqlDataAdapter = New SqlDataAdapter(comm)
Private Sub ViewCustomersForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'---open the connection and fill the dataset---
conn.Open()
dataadapter.Fill(ds, "Customers_table")
conn.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Customers_table"
'---create a combobox column---
Dim comboBoxCol As New DataGridViewComboBoxColumn
'---set the header---
comboBoxCol.HeaderText = "Tarrifs"
'---data bind it---
comboBoxCol.DataSource = Tarrifs1
'comboBoxCol.DisplayMember = "Tarrif" // when I add these rows the new Tarrif column is not visible
'comboBoxCol.ValueMember = "Tarrif" // when I add these rows the new Tarrif column is not visible
'---add a combobox column to the DataGridView control---
DataGridView1.Columns.Add(comboBoxCol)
End Sub
Private Sub Button_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim sqlCmdBuilder As New SqlCommandBuilder(dataadapter)
sqlCmdBuilder.GetUpdateCommand()
dataadapter.Update(ds.Tables("Customers_table"))
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
End Class
Hope that makes sense. Any help greatly appreciated.
A few things in this code:
dataadapter.Fill(ds, "Customers_table")
conn.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Customers_table"
'---create a combobox column---
Dim comboBoxCol As New DataGridViewComboBoxColumn
'---set the header---
comboBoxCol.HeaderText = "Tarrifs"
'---data bind it---
comboBoxCol.DataSource = Tarrifs1
First, I'm not sure what happens whenever the code attempts to fill a DataSet that already has data in it. In my code, I never assume, so I always reinitialize it each time unless I need it:
ds = new DataSet()
Next, you are setting the DataSource for comboBoxCol as Tarrifs1, but I do not see that defined anywhere. You might want to look into that.
Finally, about the SQL: Dim sql As String = "SELECT * FROM Customers" I don't know what columns are in your Customers table. Is Tarrif an actual column?
I figured half my issue out.
I configured a second data connection to pull the Tarrif drop down from the Tarrifs table and display this as part of the customer data table.
My outstanding issues now, is that I need to write the select Tarrif value back to the Customers table.
All the other updated values save, just not sure how to write the Tarrif dropdown back to my SQL table
Here is my latest code.
Imports System.Data.SqlClient
Imports System.Data.Common
Public Class ViewCustomersForm
Dim ds As DataSet = New DataSet()
Dim connStr As String = "server=barry-laptop\SQLEXPRESS; database=BillingReferenceData; integrated security=yes"
Dim sql As String = "SELECT [Customer ID] ,[Customer Name] ,[Address] ,[City] ,[County] ,[Post Code] FROM [BillingReferenceData].[dbo].[Customers]"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim comm As SqlCommand = New SqlCommand(Sql, conn)
Dim dataadapter As SqlDataAdapter = New SqlDataAdapter(comm)
Dim con As New System.Data.SqlClient.SqlConnection("server=barry-laptop\SQLEXPRESS; database=Test; integrated security=yes")
Dim strSQL As String = "SELECT * FROM Tarrifs"
Dim da As New System.Data.SqlClient.SqlDataAdapter(strSQL, con)
Private Sub ViewCustomersForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'---open the connection and fill the dataset---
conn.Open()
dataadapter.Fill(ds, "Customers_table")
conn.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Customers_table"
'---create a combobox column---
Dim comboBoxCol As New DataGridViewComboBoxColumn
'---set the header---
comboBoxCol.HeaderText = "Tarrifs"
'---data bind it---
da.Fill(ds, "Tarrifs")
comboBoxCol.DataSource = ds.Tables("Tarrifs")
comboBoxCol.DisplayMember = "Tarrif"
comboBoxCol.ValueMember = "Tarrif"
'---add a combobox column to the DataGridView control---
DataGridView1.Columns.Add(comboBoxCol)
End Sub
Private Sub Button_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim sqlCmdBuilder As New SqlCommandBuilder(dataadapter)
sqlCmdBuilder.GetUpdateCommand()
dataadapter.Update(ds.Tables("Customers_table"))
dataadapter.Update(ds.Tables("Tarrifs"))
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
End Class
I need to load a DataTable from Microsoft Access into a DataSet using OleDb. I need to load that DataSet into a DataGridView. I then need to make changes to the DataGridView and update those changes in the original DataTable in Microsoft Access.
Here is my code so far:
Public tblName As String = "Criteria"
Dim ds As New DataSet()
Dim da As OleDbDataAdapter
Dim cmdBuilder As OleDbCommandBuilder
Dim Bsource As New BindingSource
Public Sub Show_Panel_Manage_Calculations()
Panel_Manage_Calculations.Show()
Nordeen_Investing_3.con.Open()
da = New OleDbDataAdapter("SELECT Calculation, [Interval], Formula FROM " & tblName & "", Nordeen_Investing_3.con)
cmdBuilder = New OleDbCommandBuilder(da)
da.Fill(ds, "Criteria")
Bsource.DataSource = ds
DataGridView_Manage_Calculations.DataSource = Bsource
Nordeen_Investing_3.con.Close()
End Sub
Private Sub Button_Update_Click(sender As Object, e As EventArgs) Handles Button_Update.Click
Nordeen_Investing_3.con.Open()
da.Update(ds, "Criteria")
Nordeen_Investing_3.con.Close()
End Sub
Right now my data from the DataTable is not being displayed in my DataGridView.
The DataSource expects a Table, not the whole DataSet. Also you don't need the BindingSource part. Sample code:
DataGridView_Manage_Calculations.DataSource = ds.Tables(0) 'By assuming that you want the first table
im fairly new to databases in vb.net and i have just learned how to use datagridview. im gonna show some of my code for the connection and datagridview display
Public Class Form1
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet 'holds table data
Dim da As OleDb.OleDbDataAdapter 'connection to database connectionobject
Dim sql As String
Dim inc As Integer
Dim MaxRows As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = C:/AddressBook.mdb"
con.ConnectionString = dbProvider & dbSource
'alternative way of connection
'Dim fldr As String
'Environment is the user profile
'fldr = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "/AddressBook.mdb"
'dbSource = "Data Source = " & fldr
con.Open()
MsgBox("Database is now Open")
sql = "select * from tblContacts"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Addressbook")
con.Close()
MsgBox("Database is now Closed")
MaxRows = ds.Tables("AddressBook").Rows.Count
inc = -1
MsgBox(MaxRows)
TextBox1.Text = inc
DataGridView1.DataSource = ds
DataGridView1.DataMember = "AddressBook"
End Sub
End Class
i want to display in a textfield the first name based on where is the pointer is positioned after i clicked Button1, how do i do this? thank you for the replies!
You need to get that value from the data grid itself, and then show it on the form. There are other ways, but try this (and add null checks!):
Dim row as DataRow = CType(DataGridView1.CurrentRow.DataBoundItem, DataRowView).Row
myTextBox.Text = row["firstName"].ToString();
C#
var row = ((DataRowView)dataGridView1.CurrentRow.DataBoundItem).Row;
myTextBox.Text = row["firstName"].ToString();
Alternately:
If you use a DataSource, and bind the grid to that first, then fill the DataSource with the data, you can use the .Current property to get the selected row.
Edit:
Mistake in code. It should be "DataBoundItem". Not "DataItem". From memory... Also, you need to cast to string, ctype(...,string) or call .ToString().
If you bind to a list of objects, then you won't need to call the .Row, the DataBoundItem will be the actual object type, eg Customer