我创建了一个带有浮动标题的网格视图,当我滚动时该标题保持原位,但是网格视图是动态生成的,标题和列会自动适应内容。因为标题与内容分开浮动,所以它的宽度与 gridview 中的列不同,并且因为它是动态生成的,所以我不想分配预定义的宽度。我正在尝试通过c#获取gridview第一行中每一列的宽度,并设置每列的标题宽度以匹配该宽度。现在我正在尝试:
<asp:GridView CssClass="Grid" ID="gv" runat="server" OnRowDataBound="gridViewDataBind">
用 c#
protected void gridViewDataBind(object sender, GridViewRowEventArgs e)
{
for (int c = 0; c < e.Row.Cells.Count; c++)
{
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
int maxWidth = 0;
//iterate through each cell in the row
//this loop will search for the widest cell
if (e.Row.Cells[i].Text.Length > maxWidth)
{
maxWidth = e.Row.Cells[i].Text.Length;
//update the header cell to match the maxWidth found
//I multiplied by 10 to give it some length
Unit u_maxWidth = Unit.Parse((maxWidth * 16).ToString());
gv.HeaderRow.Cells[i].Width = u_maxWidth;
e.Row.Cells[i].Width = u_maxWidth;
}
if ((gv.HeaderRow.Cells[i].Text.Length) > maxWidth)
{
maxWidth = gv.HeaderRow.Cells[i].Text.Length;
//update the header cell to match the maxWidth found
//I multiplied by 10 to give it some length
Unit u_maxWidth = Unit.Parse((maxWidth * 16).ToString());
gv.HeaderRow.Cells[i].Width = u_maxWidth;
gv.Columns[i].ItemStyle.Width = u_maxWidth;
}
}
}
}
编辑:这是现在设置宽度,但是设置单元格宽度并没有给我我正在寻找的结果。当我尝试设置列宽时,我收到一个错误,即它大于集合,因为没有其他列具有宽度。