I have a small app in c#, it has a DataGridView that gets filled using:
grid.DataSource = MyDatasource array;
MyClass hold the structure for the columns, it looks something like this:
class MyDatasource
{
private string column1;
private string column2;
public MyDatasource(string arg1, string arg2)
{
this.column1 = arg1;
this.column2 = arg2;
}
public string column1
{
get
{
return this.column1;
}
set
{
this.column1 = value;
}
}
public string column2
{
get
{
return this.column2;
}
set
{
this.column1 = value;
}
}
}
Everything works fine and the DataGridView gets populated with the correct data, but now I want to hide the column2. I tried adding [Browsable(false)]
above the column declaration, that will hide it, but I also need to access the column value from code, and when I use [Browsable(false)]
and try to read the content it acts like if the column doesn't exist. If I don't use it I can read the column without problem but it's visible in the DataGridView.
How could I hide the column but still be able to read its content from code?
You have to hide the column at the grid view control rather than at the data source. Hiding it at the data source it will not render to the grid view at all, therefore you won't be able to access the value in the grid view. Doing it the way you're suggesting, you would have to access the column value through the data source as opposed to the grid view.
To hide the column on the grid view control, you can use code like this:
To access the column from the data source, you could try something like this:
I have noticed that if utilised progrmmatically it renders incomplete (entire form simply doesn't "paint" anything) if used before
panel1.Controls.Add(dataGridView);
thendataGridView.Columns["ID"].Visible = false;
will break the entire form and make it blank, so to get round that set this AFTER EG:Set that particular column's
Visible
property =false
dataGridView[ColumnName or Index].Visible = false;
Edit sorry missed the
Columns
PropertydataGridView.Columns[ColumnName or Index].Visible = false;
Just set
DataGridView.AutoGenerateColumns = false
;You need click on the arrow on top right corner (in
datagridview
) to add columns, and inDataPropertyName
you need to put a name of your property in your class.Then, after you defined your columns in
datagridview
, you can setdatagridview.datasource = myClassViewModel
.I had the same problem
Here is the Solution that might work for you. It worked for me
I"m not sure if its too late, but the problem is that, you cannot set the columns in design mode if you are binding at runtime. So if you are binding at runtime, go ahead and remove the columns from the design mode and do it pragmatically
ex..