I have DataGridView with predefined columns: id, name, phone.
In SQL Server database, I have a Users
table with these columns:
user_id, user_name, user_phone
Select data from Users
table :
SqlConnection con = new SqlConnection(connectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM users", con);
DataTable dt = new DataTable();
con.Open();
ad.Fill(dt);
DataGridView1.DataSource = dt;
con.Close();
This code works fine and shows all rows. But the main problem is DataTable also adds the Users
table columns to the DataGridView.
DataGridView output:
id | name | phone | user_id | user_name | user_phone
How to add rows from DataTable to specific pre-defined columns?
And another question is how to prevent DataTable to add SQL Server table columns to DataGridView?
Thank you.
Add the columns to your DataGridView
in the designer and set the DataPropertyName
property of each column to the data source column name you want it to bind to. In code, set the AutoGenerateColumns
property to False
before setting the DataSource
.