# Odd code behavior : C# 2008 and DataGridView



## Kreij (Jul 7, 2008)

I found this strange behavior while writing a database application.
(not all code is included for brevity)

I created a DataSet, DataAdapter and Binding Source.
Data is three fields in a table. Field 1 is primary key and an identity (unique auto-incrementing)

```
private DataSet myDataSet = new DataSet();
private SqlDataAdapter myAdapter;
private BindingSource myBindingSource;
```

I then initialized stuff to the database (in a method);

```
private void InitializeData()
{
    myAdapter = new SqlDataAdapter("select * from Table", myConnection);
    SqlCommandBuilder myBuilder = new SqlCommandBuilder(myAdapter);
    myAdapter.Fill(myDataSet, "Table");
    myBindingSource = new BindingSource(myDataSet, "Table");
}
```

I then bound a DataGridView to the data, had it auto-generate the columns and then turned off the visibilty of the columns that I did not want the user to see.

```
myDataGridView.DataSource = myBindingSource;
myDataGridView.AutoGenerateColumns = true;
myDataGridView.Columns["Column1"].Visibility = false;
myDataGridView.Columns["Column2"].Visibility = false;
```

So at this point when the DataGridView displays it should only show Column3.
So far so good.

I then did a filter on the BindingSource in another method.

```
myBindingSource.Filter = "Column3 = Something";
```

After this method runs, Column1 will always show up on the DataGridView (but not Column2), even though at this point it is supposed to be "invisible". Initial states were verifyied with debugger. After filter command, state of Column1 gets set back to visible.

I had to reset the column's visibility to false immediately following the filter command in order to get it to remain hidden.

```
myBindingSource.Filter "Column3 = Something";
myDataGridView.Columns["Column1"].Visibility = false;
```

Not sure why this is occurring, but I thought it might help someone in the event they run into this. It's also odd that it only happens for the primary key, and not Column2.


----------

