当我使用AutoGenerateColumns属性AutoGenerateColumns =“true”时,我在设置gridview的宽度时遇到问题. gridview是后面代码中的数据绑定.如果我使用gridview1.columns(0).width它会引发错误. 并且GridView1.Col
并且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有更多列,我不想通过BoundFiled添加它们,因为它们在我的情况下有所不同.
在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列宽度在浏览器中呈现,因为我们设置了每个列的宽度.我在两个项目中使用了两个方法 – 一个是通过使用AutoGenerateColumns =“false”获取绑定字段,另一个是通过设置AutoGenerateColumns =“true” – 分别在两个项目中,然后当页面在浏览器中呈现时,我使用了“查看源代码” “浏览器的功能然后意识到这两种类型的主要区别是什么.区别在于: –
style="table-layout:fixed;"
我还在gridview标签的.aspx页面中添加了以下行: –
style="table-layout:fixed;" Width="1000px"
现在它工作正常.
谢谢大家!!
