gridview是asp.net常用的顯示數(shù)據(jù)控件,對(duì)于.net開(kāi)發(fā)人員來(lái)說(shuō)應(yīng)該是非常的熟悉了。gridview自帶有許多功能,包括分頁(yè),排序等等,但是作為一個(gè).net開(kāi)發(fā)人員來(lái)說(shuō)熟練掌握利用存儲(chǔ)過(guò)程分頁(yè)或者第三方自定義分頁(yè)十分重要,這不僅是項(xiàng)目的需要,也是我們經(jīng)驗(yàn)?zāi)芰Φ奶崾?,下面我就?lái)講利用存儲(chǔ)過(guò)程分頁(yè)實(shí)現(xiàn)綁定gridview
1、執(zhí)行存儲(chǔ)過(guò)程
網(wǎng)上有許多sql分頁(yè)存儲(chǔ)過(guò)程的例子,但是你會(huì)發(fā)現(xiàn)其中有許多一部分是不能用的,例如有些使用in或者not in來(lái)分頁(yè)效率非常的低,有些sp可以分頁(yè)但是擴(kuò)展型非常差,有些效率也比較高,但是不能返回查詢(xún)記錄總數(shù),
例如下面的這個(gè)分頁(yè),盡管比較簡(jiǎn)單,但是用not in來(lái)分頁(yè)效率比較低,且查詢(xún)表已經(jīng)固定死了,無(wú)法擴(kuò)展,其實(shí)是個(gè)失敗的分頁(yè)
CREATE PROCEDURE GetProductsByPage
@PageNumber int,
@PageSize int
AS
declare @sql nvarchar(4000)
set @sql = 'select top ' + Convert(varchar, @PageSize) + ' * from test where id not in (select top ' + Convert(varchar, (@PageNumber - 1) * @PageSize) + ' id from test)'
exec sp_executesql @sql
GO
綜上我覺(jué)得這個(gè)分頁(yè)總體上來(lái)說(shuō)比較好的效率也非常的高且分頁(yè)只需要執(zhí)行一次sp,分頁(yè)支持多表多標(biāo)間查詢(xún)
ALTER PROCEDURE [dbo].[Proc_SqlPageByRownumber]
(
@tbName VARCHAR(255), --表名
@tbGetFields VARCHAR(1000)= '*',--返回字段
@OrderfldName VARCHAR(255), --排序的字段名
@PageSize INT=20, --頁(yè)尺寸
@PageIndex INT=1, --頁(yè)碼
@OrderType bit = 0, --0升序,非0降序
@strWhere VARCHAR(1000)='', --查詢(xún)條件
@TotalCount INT OUTPUT --返回總記錄數(shù)
)
AS
-- =============================================
-- Author: allen (liyuxin)
-- Create date: 2012-03-30
-- Description: 分頁(yè)存儲(chǔ)過(guò)程(支持多表連接查詢(xún))
-- Modify [1]: 2012-03-30
-- =============================================
BEGIN
DECLARE @strSql VARCHAR(5000) --主語(yǔ)句
DECLARE @strSqlCount NVARCHAR(500)--查詢(xún)記錄總數(shù)主語(yǔ)句
DECLARE @strOrder VARCHAR(300) -- 排序類(lèi)型
--------------總記錄數(shù)---------------
IF ISNULL(@strWhere,'') >''
SET @strSqlCount='Select @TotalCout=count(*) from ' + @tbName + ' where 1=1 '+ @strWhere
ELSE SET @strSqlCount='Select @TotalCout=count(*) from ' + @tbName
exec sp_executesql @strSqlCount,N'@TotalCout int output',@TotalCount output
--------------分頁(yè)------------
IF @PageIndex = 0 SET @PageIndex = 1
IF(@OrderType>0) SET @strOrder=' ORDER BY '+@OrderfldName+' DESC '
ELSE SET @strOrder=' ORDER BY '+@OrderfldName+' ASC '
SET @strSql='SELECT * FROM
(SELECT ROW_NUMBER() OVER('+@strOrder+') RowNo,'+ @tbGetFields+' FROM ' + @tbName + ' WHERE 1=1 ' + @strWhere+' ) tb
WHERE tb.RowNo BETWEEN '+str((@PageIndex-1)*@PageSize+1)+' AND ' +str(@PageIndex*@PageSize)
exec(@strSql)
SELECT @TotalCount
END
2 、封裝c#調(diào)用語(yǔ)句
我們總是習(xí)慣上對(duì)代碼進(jìn)行封裝,這樣可以提高代碼的閱讀效率,維護(hù)起來(lái)也更加方便,養(yǎng)成良好的封裝代碼習(xí)慣,我們就從初級(jí)步入了中級(jí),其實(shí)這只是個(gè)習(xí)慣而已
public static class PageHelper
{
/// summary>
/// 分頁(yè)數(shù)據(jù)
/// /summary>
/// param name="TableName">表明/param>
/// param name="RetureFields">返回字段/param>
/// param name="strWhere">條件/param>
/// param name="PageSize">每頁(yè)記錄數(shù)/param>
/// param name="CurPage">當(dāng)前頁(yè)數(shù)/param>
/// param name="RowCount">總記錄數(shù)/param>
/// param name="sortField">排序字段/param>
/// returns>/returns>
public static DataTable GetPageList(string tbName, string tbGetFields, string OrderFldName, int PageSize, int PageIndex, int OrderType, string strWhere, out int TotalCount)
{
SqlCommand cmd = new SqlCommand("Proc_SqlPageByRownumber");//存儲(chǔ)過(guò)程名稱(chēng)
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@tbName", tbName);//表名稱(chēng)
cmd.Parameters.AddWithValue("@tbGetFields", tbGetFields);//要顯示的字段名(不要加Select)
cmd.Parameters.AddWithValue("@OrderfldName", OrderFldName);//排序索引字段名
cmd.Parameters.AddWithValue("@PageIndex", PageIndex);//當(dāng)前第幾頁(yè),頁(yè)碼
cmd.Parameters.AddWithValue("@PageSize", PageSize);//每頁(yè)顯示的數(shù)據(jù)條數(shù)
cmd.Parameters.AddWithValue("@OrderType", OrderType);//設(shè)置排序類(lèi)型,非0值則降序
cmd.Parameters.AddWithValue("@strWhere", strWhere);//查詢(xún)條件,不要加where
cmd.Parameters.Add(new SqlParameter("@TotalCount", SqlDbType.Int));
cmd.Parameters["@TotalCount"].Direction = ParameterDirection.Output;
DataTable dt = RunProcedureCmd(cmd);
TotalCount = Convert.ToInt32(cmd.Parameters["@TotalCount"].Value.ToString());//返回的總頁(yè)數(shù)
return dt;
}
/// summary>
/// 執(zhí)行存儲(chǔ)過(guò)程,返回DataTable
/// /summary>
/// param name="cmd">/param>
/// returns>/returns>
public static DataTable RunProcedureCmd(SqlCommand cmd)
{
DataTable result = new DataTable();
string connectionString = ConfigurationManager.AppSettings["CONNSTRING"].ToString();
SqlConnection conn = new SqlConnection(connectionString);//你自己的鏈接字符串
try
{
if ((conn.State == ConnectionState.Closed))
{
conn.Open();
}
cmd.Connection = conn;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result);
da.Dispose();
conn.Close();
conn.Dispose();
return result;
}
catch (Exception ex)
{
conn.Close();
conn.Dispose();
throw ex;
}
}
}
3、 gridview利用第三方插件實(shí)現(xiàn)分頁(yè)
分頁(yè)現(xiàn)在比較流行的插件是aspnetpager,這是一個(gè)比較成熟的插件,網(wǎng)上也有許多的例子。
1 )、下載aspnetpager插件,然后右鍵引用。
2 )、 打開(kāi)工具箱,在選項(xiàng)卡上右鍵選擇項(xiàng)導(dǎo)入插件
3 )、拖控件到頁(yè)面,設(shè)置控件的屬性
后臺(tái)代碼
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridViewBind("");
}
}
private void GridViewBind(string sqlWhere)
{
int TotalCount;
DataTable dt = bll.GetList("stu_score", "code,name,beginTime,endTime,score", "id", this.AspNetPager1.PageSize, this.AspNetPager1.CurrentPageIndex, 1,sqlWhere, out TotalCount);
this.AspNetPager1.RecordCount = TotalCount;
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
this.AspNetPager1.CustomInfoHTML = string.Format("當(dāng)前第{0}/{1}頁(yè) 共{2}條記錄 每頁(yè){3}條", new object[] { this.AspNetPager1.CurrentPageIndex, this.AspNetPager1.PageCount, this.AspNetPager1.RecordCount, this.AspNetPager1.PageSize });
}
//GridView高亮行顯示
protectedvoid GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor,this.style.backgroundColor='#C7DEF3'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
}
}
前臺(tái)代碼
table width="100%">
tr>
td style="width: 60%; float: left;">
beginTime:asp:TextBox ID="txtBeginTime" runat="server">/asp:TextBox>
endTime:asp:TextBox ID="txtEndTime" name="mydate" runat="server">/asp:TextBox>
/td>
td style="width: 30%; float: right;">
asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click"
class="ui-button ui-widget ui-state-default ui-corner-all">/asp:Button>
asp:Button ID="btnAdd" runat="server" Text="Create" OnClientClick="javascript:return false;" />
/td>
/tr>
tr>
td colspan="2" style="width: 100%; float: left;">
asp:GridView ID="GridView1" runat="server" Width="100%" CellPadding="2" CssClass="GridViewStyle"
CellSpacing="2" AutoGenerateColumns="False">
Columns>
asp:BoundField DataField="name" HeaderText="name" />
asp:BoundField DataField="code" HeaderText="code" />
asp:BoundField DataField="beginTime" HeaderText="beginTime" />
asp:BoundField DataField="endTime" HeaderText="endTime" />
asp:BoundField DataField="score" HeaderText="score" />
/Columns>
FooterStyle CssClass="GridViewFooterStyle" />
RowStyle CssClass="GridViewRowStyle" />
SelectedRowStyle CssClass="GridViewSelectedRowStyle" />
PagerStyle CssClass="GridViewPagerStyle" />
AlternatingRowStyle CssClass="GridViewAlternatingRowStyle" />
HeaderStyle CssClass="GridViewHeaderStyle" />
/asp:GridView>
/td>
/tr>
tr>
td colspan="2">
webdiyer:AspNetPager ID="AspNetPager1" runat="server" CssClass="paginator" CurrentPageButtonClass="cpb"
OnPageChanged="AspNetPager1_PageChanged" PageSize="5" FirstPageText="首頁(yè)" LastPageText="尾頁(yè)"
NextPageText="下一頁(yè)" PrevPageText="上一頁(yè)" CustomInfoHTML="共%RecordCount%條,第%CurrentPageIndex%頁(yè) /共%PageCount% 頁(yè)"
CustomInfoSectionWidth="30%" ShowCustomInfoSection="Right">
/webdiyer:AspNetPager>
/td>
/tr>
/table>
4 、當(dāng)然你可以對(duì)你的gridview進(jìn)行樣式調(diào)整,新建gridviewSY.css
.GridViewStyle
{
border-right: 2px solid #A7A6AA;
border-bottom: 2px solid #A7A6AA;
border-left: 2px solid white;
border-top: 2px solid white;
padding: 4px;
}
.GridViewStyle a
{
color: #FFFFFF;
}
.GridViewHeaderStyle th
{
border-left: 1px solid #EBE9ED;
border-right: 1px solid #EBE9ED;
}
.GridViewHeaderStyle
{
background-color: #5D7B9D;
font-weight: bold;
color: White;
}
.GridViewFooterStyle
{
background-color: #5D7B9D;
font-weight: bold;
color: White;
}
.GridViewRowStyle
{
background-color: #F7F6F3;
color: #333333;
}
.GridViewAlternatingRowStyle
{
background-color: #FFFFFF;
color: #284775;
}
.GridViewRowStyle td, .GridViewAlternatingRowStyle td
{
border: 1px solid #EBE9ED;
}
.GridViewSelectedRowStyle
{
background-color: #E2DED6;
font-weight: bold;
color: #333333;
}
.GridViewPagerStyle
{
background-color: #284775;
color: #FFFFFF;
}
.GridViewPagerStyle table /* to center the paging links*/
{
margin: 0 auto 0 auto;
分頁(yè)控件也添加樣式,當(dāng)然gridview樣式和分頁(yè)樣式在同一個(gè)css中了
.paginator { font: 11px Arial, Helvetica, sans-serif;padding:10px 20px
10px 0; margin: 0px;}
.paginator a {padding: 1px 6px; border: solid 1px #ddd; background:
#fff; text-decoration: none;margin-right:2px}
.paginator a:visited {padding: 1px 6px; border: solid 1px #ddd;
background: #fff; text-decoration: none;}
.paginator .cpb {padding: 1px 6px;font-weight: bold; font-size:
13px;border:none}
.paginator a:hover {color: #fff; background: #ffa501;border-
color:#ffa501;text-decoration: none;}
頁(yè)面最總結(jié)果顯示樣式,
接下來(lái)我們給時(shí)間添加樣式,給時(shí)間添加樣式普遍選擇的是datePicker插件,導(dǎo)入控件所用的js和css
script src="jquery-ui-1.9.2.custom/js/jquery-1.8.3.js" type="text/javascript">/script>
script src="jquery-ui-1.9.2.custom/development-bundle/ui/jquery.ui.widget.js" type="text/javascript">/script>
script src="jquery-ui-1.9.2.custom/development-bundle/ui/jquery.ui.core.js" type="text/javascript">/script>
script src="jquery-ui-1.9.2.custom/development-bundle/ui/jquery.ui.datepicker.js" type="text/javascript">/script>link href="jquery-ui-1.9.2.custom/development-bundle/themes/ui-lightness/jquery.ui.all.css" rel="stylesheet" type="text/css" />
默認(rèn)時(shí)間插件顯示的是英文,我們給他漢化
新建initdatepicker_cn.js
function initdatepicker_cn() {
$.datepicker.regional['zh-CN'] = {
clearText: '清除',
clearStatus: '清除已選日期',
closeText: '關(guān)閉',
closeStatus: '不改變當(dāng)前選擇',
prevText: '上月',
prevStatus: '顯示上月',
prevBigText: '',
prevBigStatus: '顯示上一年',
nextText: '下月>',
nextStatus: '顯示下月',
nextBigText: '>>',
nextBigStatus: '顯示下一年',
currentText: '今天',
currentStatus: '顯示本月',
monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
monthNamesShort: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
monthStatus: '選擇月份',
yearStatus: '選擇年份',
weekHeader: '周',
weekStatus: '年內(nèi)周次',
dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
dayNamesShort: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
dayStatus: '設(shè)置 DD 為一周起始',
dateStatus: '選擇 m月 d日,DD',
dateFormat: 'yy-mm-dd',
firstDay: 1,
initStatus: '請(qǐng)選擇日期',
isRTL: false
};
$.datepicker.setDefaults($.datepicker.regional['zh-CN']);
}
前臺(tái)頁(yè)面添加jquery腳本,當(dāng)然MainContent_txtBeginTime是你時(shí)間標(biāo)簽的id,有時(shí)候你可能顯示不出來(lái),不要著急右鍵查看源文件就會(huì)發(fā)現(xiàn)控件的id和html標(biāo)簽的id不一樣,我們一定要選擇標(biāo)簽的id
script type="text/javascript">
jQuery(function () {
initdatepicker_cn();
$('#MainContent_txtBeginTime').datepicker({ changeMonth: true, changeYear: true });
});
/script>
效果圖:
如果你按照這四步去做的話(huà),一個(gè)簡(jiǎn)單實(shí)用的分頁(yè)顯示頁(yè)面就會(huì)展現(xiàn)的你的面前,歡迎大家進(jìn)行討論。
您可能感興趣的文章:- asp.net中日歷函數(shù)Calendar的使用方法
- ASP.NET中為T(mén)extBox中添加calendar.js示例代碼
- asp.net數(shù)據(jù)驗(yàn)證控件
- asp.net中使用 Repeater控件拖拽實(shí)現(xiàn)排序并同步數(shù)據(jù)庫(kù)字段排序
- ASP.NET數(shù)據(jù)綁定之DataList控件實(shí)戰(zhàn)篇
- ASP.NET數(shù)據(jù)綁定之GridView控件
- ASP.NET數(shù)據(jù)綁定之Repeater控件
- ASP.NET數(shù)據(jù)綁定GridView控件使用技巧
- ASP.NET文件上傳控件Uploadify的使用方法
- ASP.NET多文件上傳控件Uploadify的使用方法
- ASP.NET中BulletedList列表控件使用及詳解
- ASP.NET Calendar日歷(日期)控件使用方法