Dynamically formatting a GridView in ASP.net using C# 2005
I am creating a website using ASP.net with C# 2005 as the language.
In my ASP.net page, I have displayed a GridView. I have dynamically populated the GridView during runtime using Dataset and SQLDataAdapter.
Since the GridView displays ALL columns at a fixed width, it does not look pretty to me (even after applying AutoFormat style). I need to hide a few columns, change the width of a few columns and change the heading of ALL columns. I know, I can solve the first requirement of displaying only selected columns by using a Select statement with the required fieldnames only (as against Select *), but I do not know how to change the Column width and change the Column header.
I tried using the syntax like,
GridView1.Columns[0].visible = false;
GridView1.Columns[1].ItemStyle.Width = 50;
GridView1.Columns[2].HeaderText = "Result Time";
but it gave me error messages like "index was out of range".
Can anybody please help me?
Thank you.
Lalit Kumar Barik
India
Re: Dynamically formatting a GridView in ASP.net using C# 2005
If the columns are all the same width, then you have a default style being applied to every cell in the rendered table, and that's bad, unless you're the one who put that style there. By default, a GridView will expand width-wise to hold all content provided.
Secondly, how are the columns in the GridView defined? If it's in the code-behind, then it could be a bit of an operation styling them all... or you just do the smart thing and use a bit of CSS to encapsulate general styles, then add specifics as needed.
Re: Dynamically formatting a GridView in ASP.net using C# 2005
Do it in the RowDataBound event; check if the row type is header and then call on the columns by ordinal and change their headers.
If you want completely flexible styling, then use TemplateFields in your gridview instead of auto generated columns.