C# – Using a BindingSource to link a DataSet to a DataGridView, but there’s no data

ado.netbindingsourcecdataset

This is my first time working with DataSets and BindingSources, so please be gentle on me.

As part of a more complicated reporting system (I've distilled it down to a basic incarnation, but it still won't run correctly), I'm trying to pull data from a database using a DataSet problematically (that is, not set up via the designer). Here is the code I have so far:

// pull the data set
var dsReportData = new Reports2.ReportTest2();
dsReportData.BeginInit();
dsReportData.SchemaSerializationMode = SchemaSerializationMode.IncludeSchema;

// bind tha data set
BindingSource bsReportBinding = new BindingSource();
((ISupportInitialize)bsReportBinding).BeginInit();
bsReportBinding.DataMember = dsReportData.Tables[0].TableName;
bsReportBinding.DataSource = dsReportData;
bsReportBinding.ResetBindings(true);

// test this stuff
dgvTester.DataSource = bsReportBinding;

dsReportData.EndInit();
((ISupportInitialize)bsReportBinding).EndInit();

I based this on the code I saw in a .designer.cs file after setting up binding through the designer. dgvTester is just a DataGridView with the default properties created in the designer.

The ReportTest2 dataset has just one TableAdapter in it, added via designer.

Now, if I went to Data -> Preview Data in VS and previewed the ReportTest2.payments.Fill,GetData () object, it returns data just fine, same as if I ran the query I used to crate the TableAdapter in SQL Server Management Studio.

However, running the actual code results in the DataGridView getting the column names from the query result, but not the actual data. The debugger reveals that dsReportData.payments.Rows.Count == 0 (and that, yes, dsReportData.Tables[0] is payments).

I ultimately intend to use the BindingSource to provide data to a ReportViewer, but first things first is making sure there's no problems with retrieving the data before going onto debug the report.

Hopefully I'm missing something obvious here. I hope so…

Best Answer

Figured it out after some trial and error. This is the part I was missing:

var TableAdapter = new Reports2.ReportTest2TableAdapters.paymentsTableAdapter();
TableAdapter.Fill(dsReportData.payments);

I didn't see it in the code I was referencing because the designer snuck it into the .cs file instead of the .designer.cs file. This made the data appear.

Related Topic