当我使用属性autogeneratecolumns to autogeneratecolumns=“true”时,在设置gridview的宽度时遇到问题。gridview是代码隐藏中的数据绑定。如果使用gridview1.columns(0.width),则会引发错误。
而gridview1.columns.count始终为零,因为网格视图是数据绑定的。
在.aspx中:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
</asp:GridView>
在代码后面
Dim strCon As New SqlConnection("Data Source=myDataSource;Initial Catalog=myDataBaseName;Persist Security Info=True;User ID=GKRANJAN;Password=abcdef")
Dim da As New SqlDataAdapter("Select * from myTableName", strCon)
Dim ds As New DataSet
da.Fill(ds)
GridView1.DataSource = ds
GridView1.DataBind()
因此,mytablename有更多的列,我不喜欢通过boundfield添加它们,因为它们在我的情况下有所不同。
在gridview1_rowdatabound中,我使用了:
Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
Dim cell As TableCell = e.Row.Cells(0)
cell.Width = New Unit("200px")
End Sub
但这对我不起作用。请帮帮我!啊!
谢谢大家!啊!
最佳答案
我得到了它。
下面是.aspx页:
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"
style="table-layout:fixed;" Width="1000px">
<!-- Mind the above two lines to make this trick effective you must have to use both properties as is; -->
</asp:GridView>
</div>
</form>
</body>
这就是后面的代码:
Imports System.Data.SqlClient
Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strCon As New SqlConnection("Data Source=myDataSource;Initial Catalog=myDataBaseName;Persist Security Info=True;User ID=GKRANJAN;Password=abcdef")
Dim da As New SqlDataAdapter("Select * from myTableName", strCon)
Dim ds As New DataSet
da.Fill(ds)
GridView1.DataSource = ds
GridView1.DataBind()
End Sub
Private Sub GridView1_RowDataBound(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
End Class
实际上,当我们使用boundfields时,当我们设置每一列的宽度时,gridview columns width会在浏览器中呈现出来。我在两个项目中使用了两种方法-一种是使用autogeneratecolumns=“false”获取绑定字段,另一种是设置autogeneratecolumns=“true”-在两个项目中单独获取绑定字段,然后当页面在浏览器中呈现时,我使用了浏览器的“查看源”功能,然后意识到这两种类型的主要区别是什么。区别在于:
style="table-layout:fixed;"
我还在gridview标记处的.aspx页面中添加了以下行:
style="table-layout:fixed;" Width="1000px"
现在一切正常。
谢谢大家!啊!