Search code examples
c#asp.netstylesheet

Accessing styles programmatically to get values


In our application we have style sheets to define common colors etc… I wrote a quick and dirty function where I get a dataset from a stored procedure, lop off the columns that I don’t want to show, cram it into a programmatically generated DataGrid, set that DataGrid’s styles, then export it to Excel. Everyone loves the colors in the Excel output (Gasp! They match the DataGrid colors, blah blah blah…).

My final piece I would like to add to it is that I would like to programmatically access a style and grab color codes and other items from it (.IntranetGridHead) instead of hard coding them, which is what I am doing now.

int iHeaderColor = Convert.ToInt32 ("D0D7E8", 16);
DataGrid dg = new DataGrid();
dg.DataSource = dsReturnDataSet.Tables[0].DefaultView;
dg.DataBind();

dg.HeaderStyle.BackColor = System.Drawing.Color.FromArgb(iHeaderColor);
dg.HeaderStyle.Font.Bold = true;
dg.HeaderStyle.Font.Size = 10;

Obviously then whenever the company goes through another “rebranding” and the style sheet values change, the excel colors will automatically match and I will get a big (pat on the back||cookie).

Any thoughts from the C# people who know more than I (which would be most of you…)?
Thanks,
Michael


Solution

  • All Web.UI.Control objects have a .Styles property, which can be accessed as Styles["Name"]. Therefore you can do this:

    DataTable dt = LookupStyles();
    dg.Styles.Clear();
    foreach (DataRow dr in dt.Rows)
      dg.Styles.Add(dr["StyleName"].ToString(), dr["StyleValue"].ToString());
    

    I had a similar thought several months ago :) Note for this to work right, your grid must be runat="server".

    Edit: Looks like you want to READ the grid and use that... If you're using a .CssStyle and a Stylesheet (.css), you'll have to do an HTTP GET to that css file and parse it yourself.