user2628363 user2628363 -4 years ago 136
SQL Question

Binding a customized DataGridView with SQL Server database

I'm currently writing a WinForms application and I want to use a

. I know how to bind the
with a table in database like this:

using (SqlConnection con = new SqlConnection(WF_AbsPres.Properties.Settings.Default.DbConnectionString))
SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM DevInOut", con);
SqlCommandBuilder comdBuilder = new SqlCommandBuilder(a);

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

//dataGridView1.AutoGenerateColumns = false;

bindingSource1.DataSource = t;

/// bind the grid view with binding source
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;

dataGridView1.DataSource = t;

But the thing is in this way the
shows all the columns of the table. I want to add the columns in dataGridViewmanually and bind each one to a specific column in the database table. It means I don't want some columns to be shown.

How can I do that? Thanks

Answer Source

Hello for hiding columns in dataGridView you can use for example this code:

 for (int i = 0; i < (TotalNumberOfColumnsInYourTable; i++)

                dataGridView1.Columns[i].Visible = false;



            //visible columns
        dataGridView1.Columns["ColumnName"].Visible = true; 

For changing header text you can use this:

dataGridView1.Columns["OriginalColumnName"].HeaderText = "YourNewName";

If you would like to improve only SqlDataAdapter just change it to this:

 SqlDataAdapter a = new SqlDataAdapter("SELECT column1,column2,column3.. FROM DevInOut", con);

But this means that future work with columns which aren't selected wouldn┬Ęt be possible through datagridview. I wouldn't recommend it to you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download