Pass DataTable to ReportViewer - vb.net

I am trying to pass a datatable to a reportviewer which I fill by code, is there a way to do that? I tried this but nothing happened:
Dim bs As BindingSource
bs = New BindingSource()
bs.DataSource = DataTablefillbycode
Dim rs As ReportDataSource
rs = New ReportDataSource()
rs.Name = "Tabletest"
rs.Value = bs
form2.ReportViewer1.RefreshReport()
form2.ReportViewer1.Reset()
form2.ReportViewer1.LocalReport.ReportEmbeddedResource = "Test.Report1.rdlc"
form2.ReportViewer1.LocalReport.DataSources.Clear()
form2.ReportViewer1.LocalReport.DataSources.Add(rs)
form2.ReportViewer1.RefreshReport()
form2.ShowDialog()
PS : The GridView works fine with the table "Tablefillbycode"

Follow these steps to be able to pass data table to your report:
I suppose you created a Report1.rdlc in root of your project Test, so the name of its embedded resource would be Test.Report1.rdlc. Also I suppose the name of DataSet in your Report1 is DataSet1.
Put a report viewer on your Form2 and set its Dock property to Fill and set its Modifier property to Public.
In Form1 I suppose you have a DataGridView1 that you want to fill it in the Form_Load and you will use the same query that you used for creating report.
In Form1 I suppose you have a Button1 that you want to show Form2 when you click on Button1 and you want pass the data of DataGridView1 to it.
Don't forget to Imports Microsoft.Reporting.WinForms in Form1
Code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim cn = "data source=(localdb)\v11.0;initial catalog=TestDB;integrated security=True;"
Dim cmd = "SELECT Id,Name FROM Category"
Dim adapter = New SqlDataAdapter(cmd, cn)
Dim table = New DataTable()
adapter.Fill(table)
Me.DataGridView1.DataSource = table
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim form2 = New Form2()
Dim rds= New ReportDataSource("DataSet1", Me.DataGridView1.DataSource)
form2.ReportViewer1.LocalReport.DataSources.Clear()
form2.ReportViewer1.LocalReport.DataSources.Add(rds)
form2.ReportViewer1.LocalReport.ReportEmbeddedResource = "Test.Report1.rdlc"
form2.ShowDialog()
End Sub
Screenshot:

Related

Indicate combobox values with a specific ids?

I made a Sub that will populate my combobox with loan descriptions. I want to get the loancode of the loandescription on selectedindexchanged without querying again the database. Is this possible? Or should I query the database to get the indicated loancode?
Private Sub LoanProducts()
Using cmd As New SqlClient.SqlCommand("SELECT loancode,loandescription FROM LoanProducts", gSQlConn)
Dim dt As New DataTable
Dim da As New SqlClient.SqlDataAdapter
dt.Clear()
da.SelectCommand = cmd
da.Fill(dt)
For Each row As DataRow In dt.Rows
CmbLoanAvail.Items.Add(row("loandescription"))
Next row
End Using
End Sub
Expected output:
Everytime the combobox index changed, the loancode of the selected loandescription will be displayed to a textbox.
Set DataTable to combobox .DataSource property and populate .ValueMember and .DisplayMember properties with corresponding column names.
Private Sub LoanProducts()
Dim query As String = "SELECT loancode, loandescription FROM LoanProducts"
Using command As New SqlCommand(query, gSQlConn)
Dim data As New DataTable
Dim adapter As New SqlClient.SqlDataAdapter With
{
.SelectCommand = cmd
}
adapter.Fill(data)
CmbLoanAvail.ValueMember = "loancode"
CmbLoanAvail.DisplayMember = "loandescription"
CmbLoanAvail.DataSource = data
End Using
End Sub
You can use SelectionChangeCommitted event to execute some action when user made a selection
Private Sub comboBox1_SelectionChangeCommitted(
ByVal sender As Object, ByVal e As EventArgs) Handles comboBox1.SelectionChangeCommitted
Dim combobox As ComboBox = DirectCast(sender, ComboBox)
Dim selectedCode As String = combobox.SelectedValue.ToString() // returns 'loancode'
End Sub
If you could get DB rows as strongly typed classes, you could make use of ItemSource, DisplayMember and ValueMember, which would solve your problem.
In case you presented, you can use SelectedIndex property of ComboBox. Also, you need to store resultset in some class field (preferably Pirvate one). See example code below:
Public Class Form4
Private _result As DataTable
Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt As New DataTable
dt.Columns.Add("col1")
dt.Columns.Add("col2")
dt.Rows.Add("val11", "val12")
dt.Rows.Add("val21", "val22")
' at this point, we got our result from DB
_result = dt
For Each row As DataRow In dt.Rows
ComboBox1.Items.Add(row("col1"))
Next
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim selectedIndex = ComboBox1.SelectedIndex
Dim selectedRow = _result(selectedIndex)
End Sub
End Class
Keep your database objects local to the method where they are used so you can ensure that they are closed and disposed. Note the comma at the end of the first Using line. This includes the command in the same Using block.
Set the DataSource, DisplayMember and ValueMember after the Using block so the user interface code doesn't run until the connection is disposed.
To get the loan code you simply access the SelectValue of the ComboBox.
Private Sub LoanProducts()
Dim dt As New DataTable
Using gSqlConn As New SqlConnection("Your connection string"),
cmd As New SqlClient.SqlCommand("SELECT loancode,loandescription FROM LoanProducts", gSqlConn)
gSqlConn.Open()
dt.Load(cmd.ExecuteReader)
End Using
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "loandescription"
ComboBox1.ValueMember = "loancode"
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
MessageBox.Show($"The Loan Code is {ComboBox1.SelectedValue}")
End Sub

SQL Column to TextBox (from ComboBox)

I have managed to add data into a ComboBox from a column out of my SQL table, but I need the rows from across to display in the rest of the textboxes. (I hope I have worded this correctly).
Here is my code currently:
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SqlConnection("Data Source=xxxx;Initial Catalog=ltLeavers;Integrated Security=True")
Dim da As New SqlDataAdapter("SELECT * FROM dbo.mytable", con)
Dim dt As New DataTable
da.Fill(dt)
ComboBox1.DisplayMember = "DISPLAY_NAME"
ComboBox1.DataSource = dt
End Sub
The above works with no issues, all of the items add into the ComboBox but I need the corresponding rows from the other two columns which are EMAIL_ADDRESS and DEPARTMENT to add into TextBoxes from what is selected in the ComboBox.
Under the SelectedIndex_Changed event of the ComboBox; Enter the following code.
Dim dt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SqlConnection("Data Source=xxxx;Initial Catalog=ltLeavers;Integrated Security=True")
Dim da As New SqlDataAdapter("SELECT * FROM dbo.mytable", con)
da.Fill(dt)
ComboBox1.DisplayMember = "DISPLAY_NAME"
ComboBox1.DataSource = dt
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Textbox1.Text = CStr(dt.Rows(ComboBox1.SelectedIndex)("EMAIL_ADDRESS"))
Textbox2.Text = CStr(dt.Rows(ComboBox1.SelectedIndex)("DEPARTMENT"))
End Sub
You Will need to declare the data table dt outside your form's load event so it can be visible to the SelectedIndex_Changed event of the combo box.
I suggest you to use BindingSource to get it done.
Try this:
1- Declare your variable type of BindingSource with events. Also, declare your dataset will be used for data.
Dim WithEvents BS As New BindingSource
Dim ds As New DataSet
2- In your Form Load Event, query your data and bind it with both Binding Source and your ComboBox control.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SqlConnection("Data Source=xxxx;Initial Catalog=ltLeavers;Integrated Security=True")
Dim da As New SqlDataAdapter("SELECT * FROM dbo.mytable", con)
da.Fill(ds, "myPopulatedTable")
ComboBox1.DisplayMember = "id"
ComboBox1.DataSource = ds.Tables("myPopulatedTable")
'Here the new code'
BS.DataSource = ds
BS.DataMember = "myPopulatedTable"
End Sub
3- Add a Sub Procedure to display your data into other text boxes controls.
Private Sub DISPLAYRECORD(Optional ByVal table As String = "myPopulatedTable")
TextBox1.Text = ds.Tables(table).Rows(Me.BS.Position)("column1").ToString
TextBox2.Text = ds.Tables(table).Rows(Me.BS.Position)("column2").ToString()
TextBox2.Text = ds.Tables(table).Rows(Me.BS.Position)("column3").ToString()
End Sub
4- In the PositionChanged event of your Binding Source, call that sub procedure (above)
Private Sub BS_PositionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles BS.PositionChanged
DISPLAYRECORD()
End Sub
5- Finally, to sync your data with ComboBox selection, you need to change the position of that Binding Source according to the ComboBox index selection
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
BS.Position = ComboBox1.SelectedIndex
End Sub

Vb.net .net Framework 1.0 how to access data from database and show in text box

I am using .net framework 1.0 in Vb.net Win form, The question is that how can Access the data from Database and show particular column and row in the textbox.
I show data in my Gridview but I want to show some data in lable and text box.
Public Dim ConnectionString As New SqlConnection( "Data Source=.;Initial Catalog=WtfImaga;Integrated Security=True" )
Public SqlDataAdapter As New SqlDataAdapter( "SELECT * FROM wu.dbo.Students",ConnectionString )
Public SqlDataSet As New DataSet
Public SqlcommandBuil As New SqlCommandBuilder(SqlDataAdapter)
And onclick I can show data which load on the GridView but I want to show Student name on a label
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SqlDataSet.clear()
DataGridView1.DataSource = SqlDataSet
DataGridView1.DataSource = Nothing
SqlDataAdapter.Fill(SqlDataSet ,"Students")
DataGridView1.DataSource = SqlDataSet.Tables("Students")
TextBox1.Text = SqlDataAdapter.Fill(SqlDataSet,"Students.StudentId")
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SqlDataSet.clear()
DataGridView1.DataSource = SqlDataSet
DataGridView1.DataSource = Nothing
SqlDataAdapter.Fill(SqlDataSet ,"Students")
DataGridView1.DataSource = SqlDataSet.Tables("Students")
TextBox1.Text = SqlDataSet.Tables("Students").Rows(0).Item("StudentId")
End Sub
Show the student id from one of the rows in the dataset

Issue with Comobox on DataGridView

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

How to enable on BindingNavigator the AddNewItem

I'm trying to bind the BindingNavigator to a BindingSource. It works very good, but the problem is the yellow plus icon is disabled. How can I make it enabled?
I created manually with code the dataset, tableadapters and the bindingsource, but when I bind it on the bindingnavigator it shows the records but it doesn't enable "Delete" and "Add Item".
What im doing wrong?
Code from comment:
Dim connstr As String = "Data Source=" + Application.StartupPath + "\Prueba.sdf"
Dim conn As New SqlCeConnection(connstr)
Dim cmd As New SqlCeCommand("SELECT * FROM datos", conn)
Dim inscmd As New SqlCeCommand("INSERT INTO datos VALUES (#nombre,#apellido,#id)", conn)
dt = New SqlCeDataAdapter(cmd)
dt.Fill(DataSet1, "datos")
dt.InsertCommand = inscmd
BindingSource1.DataSource = DataSet1
DataGridView1.DataSource = BindingSource1
DataGridView1.DataMember = "datos"
DataGridView1.Columns("id").Visible = False
Since you provided no code, you made it really hard to try to solve your problem.
Here is an example that works. Take a new form, drop a TextBox and BindingNavigator controls on it.
Add this code:
Public Class Form1
Private bs As New BindingSource
Private ds As New DataSet
Private dt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dt.TableName = "English"
dt.Columns.Add("Words")
dt.Rows.Add("Hello")
dt.Rows.Add("Good-Bye")
ds.Tables.Add(dt)
bs.DataSource = ds
bs.DataMember = "English"
TextBox1.DataBindings.Add("Text", bs, "Words")
BindingNavigator1.BindingSource = bs
End Sub
End Class
The TextBox should have "Hello" in it. The BindingNavigator should have "1 of 2" on it, plus the Add and Delete buttons should be enabled and working.
If this doesn't help solve the problem, you will have to post some code to help us reproduce the problem.
For fun I added a 2nd text box on the form, a 2nd column in the table, and populated the two fields for both records.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dt.TableName = "English"
dt.Columns.Add("Words")
dt.Columns.Add("Spanish")
dt.Rows.Add("Hello", "Hola")
dt.Rows.Add("Good-Bye", "Adios")
ds.Tables.Add(dt)
bs.DataSource = ds
bs.DataMember = "English"
TextBox1.DataBindings.Add("Text", bs, "Words")
TextBox2.DataBindings.Add("Text", bs, "Spanish")
BindingNavigator1.BindingSource = bs
End Sub