Default.aspx
View Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>用TableAdapter创建DataTable定义及查询</title> </head> <body> <form id="form1" runat="server"> <div style="text-align: left" align="left"> <asp:Panel ID="Panel2" runat="server"> <asp:GridView ID="gvInfo" runat="server" AutoGenerateColumns="False" Font-Size="9pt" AllowPaging="True" EmptyDataText="没有相关数据可以显示!" OnPageIndexChanging="GridView1_PageIndexChanging" CellPadding="4" ForeColor="#333333" GridLines="None" onrowdatabound="gvInfo_RowDataBound"> <Columns> <asp:BoundField DataField="id" HeaderText="信息ID" /> <asp:BoundField DataField="name" HeaderText="信息主题" /> <asp:BoundField DataField="type" HeaderText="信息分类" /> <asp:BoundField DataField="content" HeaderText="发布内容" /> <asp:BoundField DataField="userName" HeaderText="发布人" /> <asp:BoundField DataField="lineMan" HeaderText="联系人" /> <asp:BoundField DataField="issueDate" HeaderText="发布时间" DataFormatString="{0:d}" /> </Columns> <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" /> <RowStyle BackColor="#FFFBD6" ForeColor="#333333" /> <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" /> <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Right" /> <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BackColor="White" /> </asp:GridView> </asp:Panel> </div> </form> </body> </html>
Default.aspx.cs
View Code
using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { dsInfoTableAdapters.tb_infTableAdapter adapter; protected void Page_Load(object sender, EventArgs e) { if (adapter == null) { adapter = new dsInfoTableAdapters.tb_infTableAdapter();//实例化TableAdapter } if (!IsPostBack) { showEmployees();//显示GridView控件中数据 } } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { gvInfo.PageIndex = e.NewPageIndex; gvInfo.DataBind(); showEmployees(); } //用GridView显示数据 protected void showEmployees() { gvInfo.DataSource = adapter.GetData();//调用TableAdapter类中的GetData()执行查询数据操作 gvInfo.DataBind();//绑定GridView控件 } protected void gvInfo_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { string gIntro = e.Row.Cells[3].Text; e.Row.Cells[3].Text = StrHelper.GetFirstString(gIntro, 12);//指定显示的内容并限定其长度 } } }