我创建与保持在适当位置时,我滚动浮动头一个gridview,然而gridview的与报头和列自动拟合的内容动态生成的。由于标头分别从内容浮动其宽度不一样在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;
}
}
}
}
编辑:现在这是将宽度,但是设置单元格宽度不给我我想要的结果。当我尝试设置列宽时,由于没有其他列具有宽度,我得到一个比集合大的错误。
谢谢,但我还是有这个问题。 gv vs gv_YourSite是我的一个错字,它们是同一个gridview。在gridview绑定数据后,我会这样做,因此它不应该成为相关文章中的问题。我已经使用新代码更新了原始帖子。再次感谢你的帮助。 –
看起来你对SO文章是正确的。 –
我更新了我的编辑的替代解决方案(黑客) – Ian