Daniel Roy
Daniel Roy

Reputation: 21

Can't move data from a DataTable to a DataGridView

The data reaches the DataTable (11 columns and 3 rows), but when I try to have it reach the DataGridView, no success (no error, just an empty "DataGridView"). Here is the portion of the relevant code:

DataGridView SecuritiesGridView1 = new DataGridView();
BindingSource bindingSource1 = new BindingSource();
SecuritiesGridView1.DataSource = bindingSource1;

String connectionString = "Data Source=|DataDirectory|\\PersonalFinanceDB.sdf;Encrypt Database=True;Persist Security Info=True";

SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter(DBcommand, connectionString);

DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;

bindingSource1.DataSource = table;
SecuritiesGridView1.DataSource = bindingSource1;
dataAdapter.Fill(table);

MessageBox.Show("Number of columns of table: " + table.Columns.Count.ToString());  // Returns 11
MessageBox.Show("Number of rows of table: " + table.Rows.Count.ToString());  // Returns 3

MessageBox.Show("Number of rows of grid: " + SecuritiesGridView1.RowCount.ToString());  // Returns 0
MessageBox.Show("Number of columns of grid: " + SecuritiesGridView1.ColumnCount.ToString());  // Returns 0

Anybody would have an idea what I might be doing wrong?

Upvotes: 0

Views: 961

Answers (3)

Mike D
Mike D

Reputation: 196

You have to make a call to SecuritiesGridView1.DataBind() after filling the table with data.

Upvotes: 0

itsmatt
itsmatt

Reputation: 31406

Regardless of how you fill the table, you need to bind the DataGridView to the DataTable.

Something like:

BindingSource myBindingSource = new BindingSource();
myDataGridView.DataSource = myBindingSource;
DataView myDataView = new DataView(myDataTable);
myBindingSource = myDataView;

should do the trick.

Then you can filter the data by changing the view, if that's what you want to do, by doing something like:

myDataView.RowFilter = (Dessert = 'Ice Cream');

or something like that, and the DataGridView will get filtered to that view.

Upvotes: 1

user484458
user484458

Reputation: 168

First fill the datatable "table" then assign the bindingsource to SecuritiesGridView1 and then call then function SecuritiesGridView1.DataBind();

Upvotes: 0

Related Questions