DoStuffZ
DoStuffZ

Reputation: 800

Gridview not listening to HeaderStyle.Width = 183

Can anyone explain this one to me. I'm trying to set the sizes of a GridView.

int totalWidth = 550;
int subWidth = totalWidth / _module.Values.Count;

with 3 modules this comes to 183, and with 2 it's 275.

Later in the code I do a:
myGrid.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
myGrid.HeaderStyle.Width = subWidth;

Now I would have assumed the width of the columns would be 183px with 3 modules, or 275 with 2. Actual sizes are: 224 + 153 + 172 = 549. The headertext of column 1 is long, but if I force it to be 183px, why does it insist of being 224? Text is column 2 is short, column 3 medio long. There is still plenty of space for all 3 headers to be squeezed a bit.

Just to be clear - I'm also doing a:
myGrid.RowStyle.HorizontalAlign = HorizontalAlign.Center;
myGrid.RowStyle.Width = subWidth;

I see the same wrong sizes in both Firefox and Chrome. I cannot get it into my stupid head how I can set a width and the column decides on another value despite my intentions.

Method in question:

private void CreateGridView()
{
GridView myGrid = new GridView();
int totalWidth = 550;
int subWidth = totalWidth / _module.Values.Count;

    #region DataTable

    DataTable dataTable = new DataTable();

    string[] dataArray = new string[_module.Values.Count];

    for (int i = 0; i < _module.Values.Count; i++)
    {
        dataArray[i] = _module.Values[i].Value.ToString("n0"); ;
    }

    for (int i = 0; i < _module.Values.Count; i++)
    {
        dataTable.Columns.Add(_module.Values[i].Text.ToString());
    }

    dataTable.Rows.Add(dataArray);

    myGrid.DataSource = dataTable;

    #endregion

    myGrid.Width = totalWidth;

    myGrid.GridLines = GridLines.None;

    myGrid.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
    myGrid.HeaderStyle.Width = subWidth;

    myGrid.RowStyle.HorizontalAlign = HorizontalAlign.Center;
    myGrid.RowStyle.Width = subWidth;

    myGrid.DataBind();

    Controls.Add(myGrid);
}

Upvotes: 1

Views: 2000

Answers (1)

csharpnumpty
csharpnumpty

Reputation: 3723

Why not set CssClass on the GridView (as well as other children of the GridView such as HeaderStyle, RowStyle and so on) and set the width on that, rather than having your UI/design elements inside of compiled code?

I would create a stylesheet, or add to an existing stylesheet with a class declaration:

.myStyle {
    width: 550px;
}

.myStyle2Modules {
     width: 750px;
}

.myStyleLotsOfModules {
     width: 1000px;
}

and then reference the class. You can then tweak the UI positions and widths on the fly by editing the CSS. You can programatically choose the CSS class in the code, but the actual definitions of those styles are in the stylesheet.

Let your code handle the functionality, nuts and bolts and implementation - let the stylesheet handle all the design elements such as colours, fonts, widths, borders and so on

Upvotes: 1

Related Questions