我是这个领域的新手,现在我面临着为动态创建的GridView设置列宽的问题。以下是我的代码:
Using dt As New DataTable()
sda.Fill(dt)
Dim mygrid As New GridView
mygrid.AutoGenerateColumns = "true"
mygrid.Font.Size = FontSize.Large
mygrid.GridLines = GridLines.None
mygrid.HeaderStyle.HorizontalAlign=HorizontalAlign.Left
mygrid.HeaderStyle.CssClass = "single_header"
mygrid.ShowFooter = True
mygrid.DataSource = dt
mygrid.Width = "700"
dt.Columns(0).ColumnName = "Specification"
dt.Columns(1).ColumnName = "Hours"
dt.Columns(2).ColumnName = "Minutes"
dt.Columns(3).ColumnName = "Cost"
mygrid.DataBind()
End Using
答案 0 :(得分:0)
您必须在GridView的RowCreated
事件中执行此操作,如below example。您可以动态添加RowCreated事件,如:
mygrid.RowDataBound += new EventHandler(GridView1_RowCreated);
VB.NET代码:
Private Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.Header Then
'For first column set to 200 px
Dim cell As TableCell = e.Row.Cells(0)
cell.Width = New Unit("200px")
'For others set to 50 px
'You can set all the width individually
For i = 1 To e.Row.Cells.Count - 1
'Mind that i used i=1 not 0 because the width of cells(0) has already been set
Dim cell2 As TableCell = e.Row.Cells(i)
cell2.Width = New Unit("10px")
Next
End If
End Sub
Asp.net代码:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.Header))
{
// For first column set to 200 px
TableCell cell = e.Row.Cells[0];
cell.Width = new Unit("200px");
// For others set to 50 px
// You can set all the width individually
for (i = 1; (i
<= (e.Row.Cells.Count - 1)); i++) {
// Mind that i used i=1 not 0 because the width of cells(0) has already been set
TableCell cell2 = e.Row.Cells[i];
cell2.Width = new Unit("10px");
}
}
}