简体   繁体   English

无法在 GridView ASP.NET 中设置列​​宽(GridView 没有数据源)

[英]Unable to set Width of Column in GridView ASP.NET (No DataSource for GridView)

An error popped up upon running the application.运行应用程序时弹出错误。

I'm trying to set the Width of the First Column of my GridView but i can't do it.我正在尝试设置 GridView 第一列的宽度,但我做不到。

Rows, Columns, Data of this GridView is not bounded to any DataSource.此 GridView 的行、列、数据不绑定到任何数据源。

//By Class Statistics

int A1Available = get.countAvailA1();
int A1Alloted = get.countUnavailA1();
int B1Available = get.countAvailB1();
int B1Alloted = get.countUnavailB1();
int B2Available = get.countAvailB2();
int B2Alloted = get.countUnavailB2();
int C1Available = get.countAvailC1();
int C1Alloted = get.countUnavailC1();

DataTable dtClass = new DataTable();
dtClass.Columns.Add("Class");
dtClass.Columns.Add("A1");
dtClass.Columns.Add("B1");
dtClass.Columns.Add("B2");
dtClass.Columns.Add("C1");

DataRow r;
r = dtClass.NewRow();
r["Class"] = "Number of Available Beds";
r["A1"] = A1Available.ToString();
r["B1"] = B1Available.ToString();
r["B2"] = B2Available.ToString();
r["C1"] = C1Available.ToString();
dtClass.Rows.Add(r);

r = dtClass.NewRow();
r["Class"] = "Number of Unavailable Beds";
r["A1"] = A1Alloted.ToString();
r["B1"] = B1Alloted.ToString();
r["B2"] = B2Alloted.ToString();
r["C1"] = C1Alloted.ToString();
dtClass.Rows.Add(r);

bedStats.DataSource = dtClass;
bedStats.DataBind();   
bedStats.Columns[1].HeaderStyle.Width = new Unit(55, UnitType.Percentage);

Used this code to set the Width.使用此代码设置宽度。 Is there any other way to?有没有其他办法? Doesn't have be bothered about the value, just setting the Width..不必担心值,只需设置宽度..

bedStats.Columns[1].HeaderStyle.Width = new Unit(55, UnitType.Percentage);

Image of Error错误图像

<code>在此处输入图片描述</code>

Setting column values will only work with TemplateField and BoundField columns.设置列值仅适用于TemplateFieldBoundField列。 Autogenerated columns are not part the column collection in the GridView.自动生成的列不属于 GridView 中的列集合。 If you want to color the Headers you need to use the OnRowDataBound event.如果要为标题着色,则需要使用OnRowDataBound事件。 Only then you can access the columns.只有这样您才能访问列。

protected void bedStats_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        e.Row.Cells[1].Width = new Unit(55, UnitType.Percentage);
        e.Row.Cells[1].BackColor = Color.Pink;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM