在http://blog.csdn.net/axjuan/archive/2007/02/25/1514344.aspx 這篇文章中,就可以在DATAVIEW中顯示記錄了,但是如果你的字段名是英文或者你想設置一下DATAVIEW的樣式,使其更美觀,就不能使用這麼簡單的代碼顯示了。
首先,如果要把標題顯示為漢字,那麼需要設置DATAVIEW的AutoGenerateColumns="false",不使用默認字段名,然後再設置asp:BoundField的HeaderText屬性,來改變列標題;另外可以設置HeaderStyle中的BackColor、Font-Size、HorizontalAlign等屬性,使其變得更加美觀。下面給一個我自己做的例子:
<%@ Page Language="VB" Debug ="true" %>
<%@ Import Namespace="System.Data.OleDb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Dim connstr As String
Dim sql As String
Dim mycommand As OleDbCommand
Dim myread As OleDbDataReader
Dim conn As OleDbConnection
Sub page_load(ByVal sender As Object, ByVal e As EventArgs)
connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("rizhi.mdb") & ";User Id=;Password=;"
conn = New OleDbConnection(connstr)
conn.Open()
sql = "select * from rizhi"
mycommand = New OleDbCommand(sql, conn)
myread = mycommand.ExecuteReader()
GridView1.DataSource = myread
GridView1.DataBind()
'Dim i As Integer
'Do While myread.Read()
' i = i + 1
'Loop
'Response.Write(i)
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>無標題頁</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<center>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" Width ="60%" Font-Size="12px" >
<Columns>
<asp:BoundField DataField="id" HeaderText="序號" >
<ItemStyle Font-Size="12px" HorizontalAlign="Left" />
<HeaderStyle BackColor="BurlyWood" Font-Size="12px" HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="rq" HeaderText="日期" >
<ItemStyle Font-Size="12px" HorizontalAlign="Left" />
<HeaderStyle BackColor="BurlyWood" Font-Size="12px" HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="n_je" HeaderText="金額" >
<ItemStyle Font-Size="12px" HorizontalAlign="Right" />
<HeaderStyle BackColor="BurlyWood" Font-Size="12px" HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="title" HeaderText="標題" >
<ItemStyle Font-Size="12px" HorizontalAlign="Left" />
<HeaderStyle BackColor="BurlyWood" Font-Size="12px" HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="content" HeaderText="內容" >
<ItemStyle Font-Size="12px" HorizontalAlign="Left" />
<HeaderStyle BackColor="BurlyWood" Font-Size="12px" HorizontalAlign="Center" />
</asp:BoundField>
<asp:HyperLinkField DataTextField="id" DataNavigateUrlFields ="id" DataNavigateUrlFormatString=" rizhi_edit.aspx?id={0} " HeaderText ="操作" DataTextFormatString ="修改" >
<ItemStyle Font-Size="12px" HorizontalAlign="Center" />
<HeaderStyle BackColor ="burlyWood" Font-Size="12px" HorizontalAlign="center" />
</asp:HyperLinkField>
</Columns>
</asp:GridView>
</center>
</div>
</form>
</body>
</html>
值得注意的是,這裡不光顯示了數據,而且還有一列是對數據的“操作”,當用戶點擊該列的時候,轉到修改頁面,並傳遞一個參數id,這裡傳遞參數的方法是 DataNavigateUrlFormatString="<% rizhi_edit.aspx?id={0} %>" ,其中0表示第一個字段,1表示第二個字段,依此類推。