Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataSet to DataGridView with pre-defined Columns

I have a DataGridView that I've setup in a WinForms project. The Columns are all defined in the designer file. When I go to run my SQL the columns in the DataGridView get replaced with the columns names in the query.

How do I keep the columns as defined by the DataGridView, and just add the rows from the dataset from the dataset to the GridView.

//Columns as they appear in the DataGridView
 Name | Address | City | State | Zip | Account Num |

//Populate the gridView
DataSet ds = Account.search(strSearch);
accountGrid.DataSource = ds.Tables[0];

//query
string sql = "SELECT distinct acctNum, name, address, city, state, zip from accounts";
return DataService.GetDataSet(sql);

//The End Result of the columns
acctNum | name | address |city | state | zip
like image 589
Scott Avatar asked Sep 11 '11 21:09

Scott


1 Answers

You need to associate columns in your DataTable with columns in your DataGridView.

Do this by updating the DataPropertyName property of a DGV column with the name of the column in the DataTable you wanted displayed in that DGV column. For example, set the DataPropertyName property in your DGV for account number to acctNum. Note you can easily do this in the designer through the "Edit Columns" dialog (bring the dialog up by right clicking your DGV in the designer and selecting "Edit Columns..." from the pop up).

Note that you'll need to set your DataGridView's AutoGenerateColumns to false to prevent it from creating columns on its own. I believe you can only make this setting through code.

like image 140
Jay Riggs Avatar answered Sep 23 '22 02:09

Jay Riggs