Link to home
Start Free TrialLog in
Avatar of MHQ
MHQ

asked on

Hiding/showing column in datagrid

I'm doing a windows aplications and need to be able to hide a column in a datagrid. I also need to be able to have it reapear. This is to be done with the checking/unchecking of a checkbox.

This is the code I have (important parts) ("result" is the datagrid in the form)

public DataTable table = new DataTable("result");
public DataView myDataView;
string columns = new String[13] {"date", "time", "c-ip", "c-port", "cs-username", "cs-method", "cs-uri-stem", "cs-uri-query", "sc-status", "sc-bytes", "cs-bytes", "s-name", "s-port"};
int i;
for(i=0; i<=12; i++)
{
table.Columns.Add(columns[i],typeof(String));
}
myDataView = new DataView(table);
result.DataSource = myDataView;

I also have a function for retreiving data and placing it in the table and it works fine. I don't want to run this every time I unhide a column again. I've tried accessing width of a column, visibility etc but in vain. How can this be done?

Regards,
MHQ
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

Avatar of MHQ
MHQ

ASKER

I've tried doing that previously but it doesn't tell me how to unhide the column at a later stage
private void ToggleColumn( int ColumnIndex) {

bool isVisible = result.Columns[ int ColumnIndex].Visible;
result.Columns[ int ColumnIndex].Visible = ( !isVisible );

}

this will hide/show your column after you fill your datagrid
Avatar of MHQ

ASKER

'System.Windows.Forms.DataGrid' does not contain a definition for 'Columns'
Set ColumnMapping to MappingType.Element
Avatar of MHQ

ASKER

myDataView.Table.Columns[2].ColumnMapping = MappingType.Element;

Doesn't work... the columns is hidden (as I have previously managed to do) but won't reappear.
Avatar of MHQ

ASKER

I got some help from a tutor and solved the problem. What I had to do was to control the width of the column using DataGridTableStyle in conjunction with some other Styles.

DataGridTableStyle tableStyle = new DataGridTableStyle();
tableStyle.MappingName = MyDataGrid.DataMember;
MyDataGrid.TableStyles.Add(tableStyle);

and to toggle:
private void Toggle()
{
DataGridColumnStyle column = MyDataGrid.TableStyles[0].GridColumnStyles["ID"];
if (column.Width==0)
{
column.Width = 75;
}
else
{
column.Width = 0;
}
}

Thanx for trying!
Regards,
MHQ
ASKER CERTIFIED SOLUTION
Avatar of Computer101
Computer101
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial