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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With