2

I have a datasource which could have a different number of columns every time it is run. I've tried to use the RowDataBound event to set the size of each column based on it's title (as below).

The problem is, if there are a lot of columns, the widths shrink. Is there a way to enforce this width regardless of how many columns I have?

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        for (int j = 0; j < NoOfColumns; j++)
        {
            string row = e.Row.Cells[j].Text;

            if (row.Contains("Date"))
            {
                e.Row.Cells[j].Width = new Unit(150);
            }
            else if (row.Contains("Transaction"))
            {
                e.Row.Cells[j].Width = new Unit(250);
            }
            else if (row.Contains("+"))
            {
                e.Row.Cells[j].Width = new Unit(300);
            }
            else if (row.Contains("Balance"))
            {
                e.Row.Cells[j].Width = new Unit(400);
            }

        }


    }
  • I'm not sure, but have you checked the type of the Units you are creating? check that it is not percentage. You can set the type by using another overload of the contructor Unit(Double, UnitType) – Amo Robb Apr 08 '21 at 10:44
  • Hi Amo, I've checked the HTML on debugging, and all the widths are set to px – user2058897 Apr 08 '21 at 11:25
  • is your gridview inside any kind of scrollview control? if you don't want the columns to shrink, you will need some kind of horizontal scrolling. If there is no scrolling, maybe the shrinking is imposed by the frame where the gridview is inserted. Have a look as well at [this link](https://stackoverflow.com/questions/5726707/set-column-width-of-a-gridview-in-asp-net), it might be of interest. – Amo Robb Apr 08 '21 at 16:49

0 Answers0