亲宝软件园·资讯

展开

JS+Ajax+Jquery实现页面无刷新分页以及分组 超强的实现

人气:0
复制代码 代码如下:

<%@ Page language="c#" Codebehind="GroupText.aspx.cs" AutoEventWireup="false" Inherits="test1.GroupText" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
    <HEAD>
        <title>GroupText</title>
        <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
        <meta name="CODE_LANGUAGE" Content="C#">
        <meta name="vs_defaultClientScript" content="JavaScript">
        <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
        <LINK href="css/wmh.css" href="css/wmh.css" type="text/css" rel="stylesheet">
        <script src="js/jquery.js" type="text/javascript"></script>
        <script src="js/Common.js" type="text/javascript"></script>
        <script src="js/getCommonTable.js" type="text/javascript"></script>
        <script src="js/GroupText.js" type="text/javascript"></script>
        <script language="javascript"><!--
        var ecid = '100001';
        var jpstr = "";
        var pageSize = 8;

        
// --></script>

    </HEAD>
    <body MS_POSITIONING="GridLayout">
        <form id="Form1" method="post" runat="server">
            <div class="listDiv" style="height:100%; PADDING-TOP: 2px">
                <table cellSpacing="0" cellPadding="0" width="100%" border="0">
                    <tr class="dg_header">
                        <td style="BORDER-RIGHT: 1px solid; BORDER-TOP: 1px solid; BORDER-LEFT: 1px solid; WIDTH: 10%; BORDER-BOTTOM: 1px solid; TEXT-ALIGN: center" >活动名称</td>
                        <td style="BORDER-RIGHT: 1px solid; BORDER-TOP: 1px solid; WIDTH: 10%; BORDER-BOTTOM: 1px solid; TEXT-ALIGN: center">发送方</td>
                        <td style="BORDER-RIGHT: 1px solid; BORDER-TOP: 1px solid; WIDTH: 10%; BORDER-BOTTOM: 1px solid; TEXT-ALIGN: center">接收方</td>
                        <td style="BORDER-RIGHT: 1px solid; BORDER-TOP: 1px solid; WIDTH: 12%; BORDER-BOTTOM: 1px solid; TEXT-ALIGN: center">发送时间</td>
                        <td style="BORDER-RIGHT: 1px solid; BORDER-TOP: 1px solid; WIDTH: 38%; BORDER-BOTTOM: 1px solid; TEXT-ALIGN: center">发送内容</td>
                        <td style="BORDER-RIGHT: 1px solid; BORDER-TOP: 1px solid; WIDTH: 10%; BORDER-BOTTOM: 1px solid; TEXT-ALIGN: center">积分</td>
                        <td style="BORDER-RIGHT: 1px solid; BORDER-TOP: 1px solid; WIDTH: 10%; BORDER-BOTTOM: 1px solid; TEXT-ALIGN: center">状态</td>
                    </tr>
                    <tr>
                        <td class="dg_line" style="BORDER-BOTTOM: 0px solid" style="BORDER-BOTTOM: 0px solid" vAlign="top" width="100%" colSpan="7"
                            height="100%">
                            <div id="divcontent" style="WIDTH: 100%; HEIGHT: 100%" align="left"></div>
                        </td>
                    </tr>
                    <tr>
                        <td class="dg_line" style="BORDER-RIGHT: 1px solid; BORDER-TOP: 1px solid; BORDER-LEFT: 1px solid; BORDER-BOTTOM: 1px solid" style="BORDER-RIGHT: 1px solid; BORDER-TOP: 1px solid; BORDER-LEFT: 1px solid; BORDER-BOTTOM: 1px solid"
                            width="100%" colSpan="10">
                            <table width="100%">
                                <tr>
                                    <td class="pgtext">共<span id="recordcount" style="COLOR: red" style="COLOR: red">0</span>条记录   
                                        目前第<span id="curpageindex" style="COLOR: red" style="COLOR: red">0</span> <font color="red">/</font><span id="pgcount" style="COLOR: red" style="COLOR: red">0</span>页   
                                        <input class="pageText" id="gototxt" type="text" maxLength="10" name="gototxt" runat="server">
                                        <input id="gotopg" type="button" class="goBtn"></td>
                                    <td align="right"><IMG id="btnfirst" style="CURSOR: hand" style="CURSOR: hand" alt="首页" src="Images/first.gif">
                                        <IMG id="btnpre" style="CURSOR: hand" style="CURSOR: hand" alt="上一页" src="Images/btn_pre.gif" > <IMG id="btnnext" style="CURSOR: hand" style="CURSOR: hand" alt="下一页" src="Images/btn_next.gif" >
                                        <IMG id="btnlast" style="CURSOR: hand" style="CURSOR: hand" alt="尾页" src="Images/btn_last.gif" >
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                </table>
            </div>
        </form>
    </body>
</HTML>

Common.js
复制代码 代码如下:

Common.js:
//时间格式化

function getDateByFormat(oldDate){
                var Dy = oldDate.getFullYear();
                var Dm = oldDate.getMonth()+1;
                var Dd = oldDate.getDate();
                if(Dm<10){
                    Dm = "0" + Dm;
                }
                if(Dd<10){
                    Dd = "0" + Dd;
                }
                var newDate = Dy+'-'+Dm+'-'+Dd;

                    return newDate;
                }
//日期-时间格式化
function getDateTimeByFormat(oldDate){
                var Dy = oldDate.getFullYear();
                var Dm = oldDate.getMonth()+1;
                var Dd = oldDate.getDate();
                var Dh = oldDate.getHours();
                var Dmi = oldDate.getMinutes();  
                var Ds    = oldDate.getSeconds();   
                if(Dm<10)
                    Dm = "0" + Dm;
                if(Dd<10)
                    Dd = "0" + Dd;

                if(Dh<10)
                 Dh = "0" + Dh;
                if(Dmi<10)
                    Dmi = "0" + Dmi;
                if(Ds<10)
                    Ds = "0" + Ds;

                var newDate = Dy+'-'+Dm+'-'+Dd+' '+Dh+':'+Dmi+':'+Ds;
                    return newDate;
                }

//只能输入数字
function txtnumber()
            {
                if ((event.keyCode >57) || (event.keyCode <48))
                    return false;else return true;
            }

        //只能输入数字和字母

    function txtnumchar()
            { //65- 90 97-122
                var kcode = event.keyCode;
                if (kcode >= 48 && kcode <= 57)
                    return true;
                else if(kcode >= 65 && kcode <= 90)
                    return true;
                else if (kcode >= 97 && kcode <= 122)
                    return true;
                else
                    return false;
            }

getCommonTable.js
复制代码 代码如下:

getCommonTable.js
//获取table头
         function getTableHeadByWidth(widthSize,ids){
         var Tableone = "<table id='tab"+ids+"' border='0' cellspacing='0' cellpadding='0' ";
         var Tabletwo = ">";
         if (widthSize == "")
         return Tableone + Tabletwo;
         else
         return Tableone+"width="+widthSize+Tabletwo;

        }

        
//获取第一个tr td 传一个宽度值
        function getTrAndTdFirstByCWidth(classname,widthSize){
         var tdone = " <tr ";
         var tdtwo = "><td style="BORDER-BOTTOM: 1px solid;" style="BORDER-BOTTOM: 1px solid;" align='center' ";
         var tdthr = " > ";
         if (classname =="")
         tdone += tdtwo;
         else
         tdone+=" class ='"+classname+"' "+tdtwo;

         if (widthSize == "")
         tdone += tdthr;
         else
         tdone += " width="+widthSize+tdthr;

         return tdone;
        }

        //获取下一个TD,传一个宽度值
        function getTdNextByWidth(widthSize){
         var tdone = " </td><td style=" BORDER-BOTTOM: 1px solid" style=" BORDER-BOTTOM: 1px solid" align='center' ";
         var tdtwo =">";
         if (widthSize =="")
         return tdone+tdtwo;
         else
         return tdone+"width="+widthSize+tdtwo;
        }

        //获取最后一个td
        function getTdLastByWidth(widthSize){
         var tdone = " </td><td style=" BORDER-BOTTOM: 1px solid" style=" BORDER-BOTTOM: 1px solid" align='center' ";
         var tdtwo =">";
         if (widthSize =="")
         return tdone+tdtwo;
         else
         return tdone+"width="+widthSize+tdtwo;
        }
        //获取最后一个tr/td
        function getTrAndTdLast(){
         return " </td></tr>";
        }

        
        //获取table尾
        function getTableLast(){
         return "</table>";
        }

        //获取img
        function getImgByParams(imgUrl,altstr,eventName,eventParams,imgid){
         var one = "<img border='0' style="CURSOR: hand" style="CURSOR: hand"";
         if (imgUrl != "")
         one += "src='"+imgUrl+"'";
         if (altstr != "")
         one += "alt='"+altstr+"'";
         if(imgid != "")
         one += "id='"+imgid+"'";

         one += "onclick='"+eventName+"("+eventParams+");'> ";

         return one
        }

//--------排序---------------------------
            //通过字段的内容排序
        SortByBtnidAndCellName=function(btnId,cellName,celltype){
            var way =    getOpType(btnId);//0为正。1为倒
            var ds = userdata.value;
            var sortarr= new Array();
            if ((ds!= null) && (typeof(ds) == "object")){
             var len = ds.Rows.length;
             if(celltype=='S' || celltype=='N'){
                        for(var j=0;j<len;j++){
                            sortarr[j] = ds.Rows[j][cellName];//.substr(0,1);//通过字符
                            }
                    }else if(celltype=='D'){
                        for(var i=0;i<len;i++){
                                    sortarr[i] = getDateByFormat(ds.Rows[i][cellName]);//通过日期
                            }
                    }
                if(sortarr!=''){
                    var indexarr = new Array();
                    indexarr = getSortArray(sortarr,celltype);//得到新的排序规则
                    if(indexarr != ''){
                        setSortAginbyWay(indexarr,way);
                    }
                }
            }
        }

        //获得排序
        getOpType=function(btnid){//返回0正序,1为倒序
            var imgName= $("#"+btnid).attr("src");
            var wz = imgName.indexOf('.gif');
            var oldImg =imgName.substr(wz-9,9);
            if(oldImg=='sort_desc'){//当前是倒序或未排序,需要正序sort_ascc
                $("#"+btnid).attr("src","../Images/sort_ascc.gif");
                return 0;
            }else{
                $("#"+btnid).attr("src","../Images/sort_desc.gif");
                return 1;
            }

        }
        //按JS Sort排序 获得新的排序规则
        getSortArray=function (sortdatearr,celltype){// 参数为array
                var sortstr = '';
                for(var k=0;k<sortdatearr.length;k++){
                if(sortstr=='')
                        sortstr=sortdatearr[k];
                    else
                        sortstr+='^%^'+sortdatearr[k];
                }
                var newsortdate =sortdatearr;
                var len = sortdatearr.length;

                    if(celltype =='S' || celltype =='D')
                        newsortdate.sort();//字符排序
                    else{ //数字排序
                        for(var i=0;i<len;i++){
                            var tmp =0;
                            for(var j=i+1;j<len;j++){
                                if(newsortdate[i]>newsortdate[j]){
                                    tmp = newsortdate[i];
                                    newsortdate[i] = newsortdate[j];
                                    newsortdate[j] =tmp;
                                }
                            }
                        }
                    }

             var tmpsortdate =sortstr.split('^%^')

             var resultarr = new Array();
             for(var i = 0;i<len;i++){
                    for(var j = 0;j<len;j++){
                     if(newsortdate[i]==tmpsortdate[j]){
                            resultarr[i] = j;
                            tmpsortdate[j] ='||||||||';
                            break;
                     }
                    }
             }

             return resultarr;
        };

//--------------------end-------------------------------
//删除重复的手机号码
SplitRepeatMobile=function(mobile){
    var mob=mobile;
    for(var i=0;i<mob.length;i++){
        for(var j=i+1;j<mob.length;j++){
            if(mob[i]==mob[j]){
                mob.splice(j,1);
            }
        }
    }
    return mob;
}


复制代码 代码如下:

GroupText.js

        var totalCount;//总页
var userdata;//数据对象
    $(document).ready(function(){            

            
            if(ecid !=""){
             firstSearch(ecid);
            }

            $("#ddlCsList").change(function(){
             ecid = $.trim($("#ddlCsList").val());
             firstSearch(ecid);
            });

            $("#btnfirst").click(function(){
         firstSearch(ecid);
            });

            $("#btnnext").click(function(){
             nextSearch(ecid);
            });

            $("#btnpre").click(function(){
             preSearch(ecid);
            });

            $("#btnlast").click(function(){
             lastSearch(ecid);
            });

            $("#gotopg").click(function(){
             gotoSearch(ecid);
            });

        

});
//绑定数据
        function binddata(udata)
        {
         jpstr ="";//这样的目的是清空,很有用的一步

         var ds = udata.value;

                    if ((ds!= null) && (typeof(ds) == "object"))
                    {
                     //alert( ds.Rows[0].ItemName )
                     var c = ds.Rows.length;
                     var newarr = getdataarr(udata);
                     for(var k = 0; k<newarr.length;k++){

                            
                            var tmp = newarr[k];
                            jpstr +="<tr><td style=" BORDER-BOTTOM: 1px solid" style=" BORDER-BOTTOM: 1px solid"><IMG id ='"+ds.Rows[tmp].srId+"' onclick=showOrHide("+ds.Rows[tmp].srId+") style="CURSOR: hand" style="CURSOR: hand" src="Images/uuu.gif" src="Images/uuu.gif"><B>"+ds.Rows[tmp].ItemName+"</b></td></tr><tr><td>"
                            var jpstrA="";
                            for(var i=tmp; i<c; i++)
                            {

                             if(ds.Rows[tmp].ItemName == ds.Rows[i].ItemName ){
                                            jpstrA += getTrAndTdFirstByCWidth("dg_item","10%") +
                                                            ""+ds.Rows[i].ItemName + getTdNextByWidth("10%") +
                                                            ""+ds.Rows[i].SendMod + getTdNextByWidth("10%") +
                                                            ""+ds.Rows[i].RecvMod + getTdNextByWidth("12%") +
                                                            ""+getDateByFormat(ds.Rows[i].SendDate) + getTdNextByWidth("38%") +
                                                            ""+ds.Rows[i].SendMsg + getTdNextByWidth("10%") +
                                                            ""+ds.Rows[i].JfValue + getTdLastByWidth("10%") +
                                                            ""+getTextByStatus(ds.Rows[i].SendStatus) +
                                                            "" + getTrAndTdLast();
                                        }
                                }    

                                jpstr +=getTableHeadByWidth("100%",ds.Rows[tmp].srId) + jpstrA + getTableLast();

                                jpstr += "</td></tr>";

                        }
                        jpstr ="<table width=100%>"+jpstr+"</table>";

                            

                                document.getElementById("divcontent").innerHTML = jpstr;
                                //alert(jpstr);

                }
                else
                {
                    document.getElementById("divcontent").innerHTML = "";    
                }

}
showOrHide=function(ids){
            $("#tab"+ids).toggle();
            var imgName= $("#"+ids).attr("src");

                var wz = imgName.indexOf('.gif');
                var oldImg =imgName.substr(wz-3,3);

                if(oldImg=='uuu')//选择
                        $("#"+ids).attr("src","Images/eee.gif");
                else{
                    $("#"+ids).attr("src","Images/uuu.gif");

                    }

}
function getdataarr(udata){
var ds = udata.value;
            var resultArr= new Array();
            var dsstr='';
            for(var i=0; i<ds.Rows.length; i++){
                resultArr[i] = $.trim(ds.Rows[i].ItemName);
                if(dsstr=='')
                 dsstr =$.trim(ds.Rows[i].ItemName);
                 else
                 dsstr+='^%^'+$.trim(ds.Rows[i].ItemName)
            }

            splitStr(resultArr)

            var newArr = new Array();
            var temparr=dsstr.split('^%^')
            for(var k=0;k<resultArr.length;k++){
                for(var m=0;m<temparr.length;m++){
                    if(resultArr[k]==temparr[m]){
                        newArr[k]=m;
                        break;
                    }
                }
            }

            return newArr;
}
splitStr= function(oldarr){
                var nArr=oldarr;
                var isok=false;
                for(var l=0;l<nArr.length;l++){
                    for(var j=l+1;j<nArr.length;j++){
                    if(nArr[l]==nArr[j]){
                        nArr.splice(j,1);
                        isok=true;
                        }    
                }
            }

            if(isok)
                splitStr(nArr);

}
function getTextByStatus(status){
            if(status==0){
             return "<font color='blue'>启用</font>";
}else{
             return "<font color='red'><B>禁用</B></font>";
}
}
function getImgByStatus(status){
if(status==0){
return "../Images/gz2.gif";
}else{
return "../Images/gz1.gif";
}
}
function getTxtByStatus(status){
if(status==0){
return "我要禁用";
}else{
return "我要启用";
}
}
//第一页
        function firstSearch(ecid)
        {
         if (ecid != ""){
                 totalCount = Interactive.GetCmdSMSlogCount("1=1").value;
                    userdata = Interactive.PageingOpenCmdSMSLog(1,pageSize);//Interactive.getInteractiveSMSByEcid(ecid,pageSize,1,totalCount);

                    binddata(userdata);

                    $("#recordcount").html(totalCount.toString());//curpageindex
                    $("#curpageindex").html(totalCount==0?'0':1);
                    if (totalCount % pageSize ==0)
                    {
                     $("#pgcount").html((totalCount / pageSize).toString());
                    }else{
                     $("#pgcount").html(parseInt(totalCount / pageSize)+1);
                    }

                }
        }
    //下一页
        function nextSearch(ecid){
         if (ecid != ""){
         var curpg =$("#curpageindex").html();//得到当前页
         var pgCount = $("#pgcount").html();//得到总的页数
         if (curpg < pgCount){
                        totalCount = Interactive.GetCmdSMSlogCount('1=1').value;
                     userdata = Interactive.PageingOpenCmdSMSLog(parseInt(curpg)+1,pageSize);

                        binddata(userdata);
                        $("#recordcount").html(totalCount);//curpageindex
                        $("#curpageindex").html(parseInt(curpg)+1);
                        if (totalCount % pageSize ==0)
                        {
                        $("#pgcount").html(totalCount / pageSize);
                        }else{
                            $("#pgcount").html(parseInt(totalCount / pageSize)+1);
                        }
                    }else{
                     alert("当前已经是尾页了!");
                    }
                }
        }
    //上一页
        function preSearch(ecid){
         if (ecid != ""){
         var curpg =$("#curpageindex").html();//得到当前页
         var pgCount = $("#pgcount").html();//得到总的页数
         if (curpg > 1 ){
                        totalCount = Interactive.GetCmdSMSlogCount('1=1').value;
                     userdata = Interactive.PageingOpenCmdSMSLog(parseInt(curpg)-1,pageSize);
                        binddata(userdata);
                        $("#recordcount").html(totalCount);//curpageindex
                        $("#curpageindex").html(parseInt(curpg)-1);
                        if (totalCount % pageSize ==0)
                        {
                        $("#pgcount").html(totalCount / pageSize);
                        }else{
                            $("#pgcount").html(parseInt(totalCount / pageSize)+1);
                        }
                    }else{
                         alert("当前已经是首页了!");
                    }
                }
        }
        //尾页
        function lastSearch(ecid){
         if (ecid != ""){
         var curpg =$("#curpageindex").html();//得到当前页
         var pgCount = $("#pgcount").html();//得到总的页数
         if (curpg < pgCount ){
                        totalCount = Interactive.GetCmdSMSlogCount('1=1').value;
                     userdata = Interactive.PageingOpenCmdSMSLog(pgCount,pageSize);
                        binddata(userdata);
                        $("#recordcount").html(totalCount);//curpageindex
                        $("#curpageindex").html(pgCount);
                        if (totalCount % pageSize ==0)
                        {
                        $("#pgcount").html(totalCount / pageSize);
                        }else{
                            $("#pgcount").html(parseInt(totalCount / pageSize)+1);
                        }
                    }
                }

        }

        //跳转指定页
        function gotoSearch(ecid){
         if (ecid != ""){
         var curpg =$("#curpageindex").html();//得到当前页
         var pgCount = $("#pgcount").html();//得到总的页数
         var pggoto =$("#gototxt").val();
         var reg = /[^\d]/g;
                    if (($.trim(pggoto) != "") && !(reg.test(pggoto))){
                        if ((parseInt(curpg) != parseInt(pggoto)) && (pggoto <= pgCount)){
                            totalCount = Interactive.GetCmdSMSlogCount('1=1').value;
                            userdata = Interactive.PageingOpenCmdSMSLog(pggoto,pageSize);
                            binddata(userdata);
                            $("#recordcount").html(totalCount);//curpageindex
                            $("#curpageindex").html(pggoto);
                            if (totalCount % pageSize ==0)
                            {
                            $("#pgcount").html(totalCount / pageSize);
                            }else{
                                $("#pgcount").html(parseInt(totalCount / pageSize)+1);
                            }
                        }
                    }else{
                        alert("请输入正确的数字!");
                    }

                }

        }

        //刷新
        function Refresh(ecid){
         if (ecid != ""){
         var curpg =$("#curpageindex").html();//得到当前页

                    totalCount = Interactive.GetCmdSMSlogCount('1=1').value;
                    userdata = Interactive.PageingOpenCmdSMSLog(curpg);
                    binddata(userdata);
                    $("#recordcount").html(totalCount);//curpageindex
                    $("#curpageindex").html(curpg);
                    if (totalCount % pageSize ==0)
                    {
                    $("#pgcount").html(totalCount / pageSize);
                    }else{
                        $("#pgcount").html(parseInt(totalCount / pageSize)+1);
                    }

                    
                }

        }

复制代码 代码如下:

GroupText.aspx.cs:
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
Ajax.Utility.RegisterTypeForAjax(typeof(DataAccess.Interactive));
}

复制代码 代码如下:

Interactive.cs:
[Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.Read)]
        public DataTable PageingOpenCmdSMSLog(int pgindex,int pageSize)
        {
            int pageIndex=pgindex;
            DataTable dt = new DataTable ();
            JSONHelper json = new JSONHelper();
            int count = GetCmdSMSlogCount("1=1");
            dt = GetDataByPager2000("SendAndRecvData S left join InteractiveSMS I on (S.ItemId=I.Id AND S.ECID=I.ECID)","srId","1=1",pageSize,pageIndex,"srId",1,
                "S.srId,I.ItemName,S.SendMod,S.RecvMod,S.SendDate,S.SendMsg,S.JfValue,S.SendStatus",count);
            return dt;
        }

        [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.Read)]
        public int GetCmdSMSlogCount(string where)
        {
            try
            {
                int count = ReturnSQL("select count(*) from SendAndRecvData S left join InteractCommand I on(S.ItemId=I.Id AND S.ECID=I.ECID) where "+where);
                return count;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 分页获取数据列表 适用于SQL2000
        /// </summary>
        /// <param name="tablename">表名</param>
        /// <param name="key">主键</param>
        /// <param name="where">查询条件</param>
        /// <param name="pagesize">每页记录数</param>
        /// <param name="pageindex">页索引</param>
        /// <param name="orderfield">排序字段</param>
        /// <param name="ordertype">排序方式 1=ASC 0=DESC</param>
        /// <param name="fieldlist">查找的字段</param>
        /// <param name="recordcount">总记录数</param>
        /// <returns></returns>
        public static DataTable GetDataByPager2000(string tablename, string key, string where, int pagesize, int pageindex, string orderfield, int ordertype, string fieldlist, int recordcount)
        {
            string cmd = "ProcCustomPage";
            SqlParameter[] para = new SqlParameter[9];
            para[0] = new SqlParameter("@Table_Name", tablename);
            para[1] = new SqlParameter("@Sign_Record", key);
            para[2] = new SqlParameter("@Filter_Condition", where);
            para[3] = new SqlParameter("@Page_Size", pagesize);
            para[4] = new SqlParameter("@Page_Index", pageindex);
            para[5] = new SqlParameter("@TaxisField", orderfield);
            para[6] = new SqlParameter("@Taxis_Sign", ordertype);
            para[7] = new SqlParameter("@Find_RecordList", fieldlist);
            para[8] = new SqlParameter("@Record_Count", recordcount);

            return ExecuteDataSet(CommandType.StoredProcedure, cmd, para).Tables[0];

        }
        public static DataSet ExecuteDataSet(CommandType cmdType, string cmdText, params SqlParameter[] para)
        {
            try
            {
                using (SqlConnection con = new SqlConnection(CONN_STRING))
                {
                    SqlDataAdapter adapter = new SqlDataAdapter();

                    using (SqlCommand cmd = new SqlCommand())
                    {
                        DataSet ds = new DataSet();
                        PrepareCommand(con, cmd, cmdType, cmdText, para);
                        adapter.SelectCommand = cmd;
                        adapter.Fill(ds);

                        return ds;
                    }
                }
            }
            catch(Exception ex)
            {
                string d=ex.ToString();
                return null;
            }
        }
        /// <summary>
        /// 建立SqlCommand
        /// </summary>
        /// <param name="con">SqlConnection 对象</param>
        /// <param name="cmd">要建立的Command</param>
        /// <param name="cmdType">CommandType</param>
        /// <param name="cmdText">执行的SQL语句</param>
        /// <param name="cmdParms">参数</param>
        private static void PrepareCommand(SqlConnection con, SqlCommand cmd, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
        {
            if (con.State != ConnectionState.Open)
                con.Open();

            cmd.Connection = con;
            cmd.CommandType = cmdType;
            cmd.CommandText = cmdText;

            if (cmdParms != null)
                foreach (SqlParameter para in cmdParms)
                    cmd.Parameters.Add(para);
        }

加载全部内容

相关教程
猜你喜欢
用户评论