标签:style blog http java width 数据
前面是写了两篇,但都不怎么完整,比较才刚开始学这个,都是摸着石头过河,一步一步的来。这两天终于把DataGrid的增删改查融合到一起了,所以分享一下,希望对和我一样的初学者都点帮助。
直接主题吧。
还是想说数据表吧,我建了一个很简单的表Rex_Test
ID | 自增序号 |
tName | 姓名 |
tEmail | 邮箱 |
前台代码:
Default.aspx
<%@ 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></title> <link rel="stylesheet" type="text/css" href="jquery-easyui-1.3.6/themes/default/easyui.css" /> <link rel="stylesheet" type="text/css" href="jquery-easyui-1.3.6/themes/icon.css" /> <link rel="stylesheet" type="text/css" href="demo.css" /> <script type="text/javascript" src="jquery-easyui-1.3.6/jquery.min.js"></script> <script type="text/javascript" src="jquery-easyui-1.3.6/jquery.easyui.min.js"></script> <script type="text/javascript"> function getQueryParams(queryParams) { var tkey = document.getElementById("tkey").value; //alert(tkey); //$("#quanxian").combobox("getValue"); queryParams.tkey = tkey; return queryParams; } //增加查询参数,重新加载表格 function reloadgrid() { //查询参数直接添加在queryParams中 var queryParams = $('#tt').datagrid('options').queryParams; getQueryParams(queryParams); $('#tt').datagrid('options').queryParams = queryParams; $("#tt").datagrid('reload'); } function add() { //清空内容 $('#fm').form('clear'); $('#dlg').dialog('open').dialog('setTitle', '添加邮箱'); document.getElementById("test").value = "add"; } //修改 function editUser() { var row = $('#tt').datagrid('getSelected'); if (row == null) { $.messager.alert("提示", "请选择要修改的行!", "info"); } if (row) { //获取要修改的字段 $('#tName').val(row.tName); $('#tEmail').val(row.tEmail); $('#dlg').dialog('open').dialog('setTitle', '修改邮箱'); document.getElementById("test").value = "modify"; $('#fm').form('load', row); } } function removeUser() { var test = document.getElementById("test").value = "delete"; var row = $('#tt').datagrid('getSelected'); if (row == null) { $.messager.alert("提示", "请选择要删除的行!", "info"); } if (row) { $.messager.confirm('提示', '你确定要删除这条信息吗?', function (r) { if (r) { $('#fm').form('submit', { url: 'Handler5.ashx/ProcessRequest?ID=' + row.ID + "&test=" + test, onSubmit: function () { //return $(this).form('validate'); }, success: function (result) { if (result.indexOf("T") == 0) { $('#dlg').dialog('close'); //$('#tt').datagrid('clearSelections'); //清空选中的行 $.messager.alert("提示", "恭喜您,信息删除成功!", "info"); //alert('恭喜您,信息删除成功!') // close the dialog $('#tt').datagrid('reload'); //$('#fm').form('submit'); } else { $.messager.alert("提示", "删除失败,请重新操作!", "info"); //alert('添加失败,请重新操作!') return; //$('#fm').form('submit'); } } }); } }) } } function saveUser() { var tName = document.getElementById("tName").value; var tEmail = document.getElementById("tEmail").value; //alert(tName + "<br/>" + tEmail); var test = document.getElementById("test").value; if (test == "add") { $('#fm').form('submit', { url: "Handler5.ashx?test=" + test + "&tName=" + tName + "&tEmail=" + tEmail, onSubmit: function () { return $(this).form('validate'); }, success: function (result) { //alert(result); if (result.indexOf("T") == 0) { $('#dlg').dialog('close'); $.messager.alert("提示", "恭喜您,信息添加成功", "info"); //alert('恭喜您,信息添加成功!') // close the dialog $('#tt').datagrid('reload'); //$('#fm').form('submit'); } else { $.messager.alert("提示", "添加失败,请重新操作!", "info"); return; //alert('添加失败,请重新操作!') } } }); } else { var row = $('#tt').datagrid('getSelected'); if (row) { //获取要修改的字段 var ID = row.ID; //alert(ID); } $('#fm').form('submit', { url: "Handler5.ashx?test=" + test + "&ID=" + ID + "&tName=" + tName + "&tEmail=" + tEmail, onSubmit: function () { return $(this).form('validate'); }, success: function (result) { if (result.indexOf("T") == 0) { $('#dlg').dialog('close'); //$('#tt').datagrid('clearSelections'); //清空选中的行 $.messager.alert("提示", "恭喜您,信息修改成功", "info"); //alert('恭喜您,信息添加成功!') // close the dialog $('#tt').datagrid('reload'); //$('#fm').form('submit'); } else { $.messager.alert("提示", "修改失败,请重新操作!", "info"); return; //alert('添加失败,请重新操作!') } } }); } } </script> </head> <body> <form id="fm" method="post"> <div> <%--表格显示区--%> <table id="tt" title="设置" class="easyui-datagrid" style="width: auto; height: 660px;" idField="ID" pagination="true" data-options="iconCls:'icon-save',rownumbers:true,url:'Handler5.ashx/ProcessRequest',pageSize:20, pageList:[20,30,40,50],method:'get',toolbar:'#tb',striped:true" fitcolumns="true"> <%--striped="true"--%> <%-- 表格标题--%> <thead> <tr> <th data-options="field:'ID',checkbox:true"> </th> <th data-options="field:'tName',width:100"> 姓名 </th> <th data-options="field:'tEmail',width:320,align:'center'"> 邮箱 </th> </tr> </thead> <%--表格内容--%> </table> <%--功能区--%> <div id="tb" style="padding: 5px; height: auto"> <%-- 包括添加,修改、删除 --%> <div style="margin-bottom: 5px"> <a href="javascript:void(0)" onclick="add()" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true"></a> <a href="javascript:void(0)" onclick="editUser() " class="easyui-linkbutton" data-options="iconCls:'icon-edit',plain:true"></a> <a href="javascript:void(0)" onclick="removeUser()" class="easyui-linkbutton" data-options="iconCls:'icon-remove',plain:true"></a> </div> <%-- 查找信息 --%> <div> 姓名: <input id="tkey" /> <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-search'" onclick="reloadgrid()"> Search</a> </div> </div> <div id="dlg" class="easyui-dialog" style="width: 400px; height: auto; padding: 10px 20px" data-options="closed:true,buttons:'#dlg-buttons'"> <%--closed="true" buttons="#dlg-buttons"--%> <div class="ftitle"> 邮箱信息</div> <div class="fitem"> <label> 姓名:</label> <input id="tName" name="tName" class="easyui-validatebox" data-options="required:true" /> </div> <div class="fitem"> <label> 邮箱:</label> <input id="tEmail" name="tEmail" class="easyui-validatebox" data-options="required:true" /> <input name="Test" id="test" type="hidden" /> <input name="ID" id="ID" type="hidden" /> <input id="key" name="key" onkeydown="if(event.keyCode==13)reloadgrid()" type="hidden" /> </div> </div> <div id="dlg-buttons"> <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-ok'" onclick="saveUser()"> 保存</a> <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-cancel'" onclick="javascript:$('#dlg').dialog('close')">关闭</a> </div> </div> </form> </body> </html>
Handler5.ashx
<%@ WebHandler Language="C#" Class="Handler5" %> using System; using System.Web; using System.Data; using System.Data.SqlClient; using System.IO; using System.Text; public class Handler5 : IHttpHandler { public void ProcessRequest(HttpContext context) { string command = context.Request.QueryString["test"];//前台传的标示值 if (command == "add") {//调用添加方法 Add(context); } else if (command == "modify") {//调用修改方法 Modify(context); } else if (command == "delete") { Delete(context); } else { Query(context); } //Query(context); } public bool IsReusable { get { return false; } } public void Add(HttpContext context) { context.Response.ContentType = "text/plain"; string xx = string.Empty; string tname = context.Request.QueryString["tName"]; string temail = context.Request.QueryString["tEmail"]; SqlHelp sqla = new SqlHelp(); string sqlString = "insert into Rex_Test(tName,tEmail) values('" + tname + "','" + temail + "')"; bool aa= sqla.ExecuteNonQuery(sqlString); sqla.SqlClose(); if (aa) { xx = "True"; } else { xx="False"; } context.Response.Write(xx); } public void Modify(HttpContext context) { context.Response.ContentType = "text/plain"; string yy = string.Empty; string id = context.Request.QueryString["ID"]; string tname = context.Request.QueryString["tName"]; string temail = context.Request.QueryString["tEmail"]; SqlHelp sqlb = new SqlHelp(); string sqlString = "update Rex_Test set tName='"+tname+"',tEmail='"+temail+"' where ID='"+id+"'"; bool bb= sqlb.ExecuteNonQuery(sqlString); sqlb.SqlClose(); if (bb) { yy = "True"; } else { yy = "False"; } context.Response.Write(yy); } public void Delete(HttpContext context) { context.Response.ContentType = "text/plain"; string zz = string.Empty; string id=context.Request.QueryString["ID"]; SqlHelp sqlc = new SqlHelp(); string strfacc = "delete from Rex_Test where ID='"+id+"'"; sqlc.ExecuteNonQuery(strfacc); sqlc.SqlClose(); context.Response.Write("True"); } /// <summary> /// 查询记录 /// </summary> /// <param name="context"></param> public void Query(HttpContext context) { context.Response.ContentType = "text/plain"; //=============================================================== string tkey; tkey = ""; //获取前台传来的值 if (null != context.Request.QueryString["tkey"]) {//获取前台传来的值 tkey = context.Request.QueryString["tkey"].ToString().Trim(); } //================================================================ //获取分页和排序信息:页大小,页码,排序方式,排序字段 int pageRows, page; pageRows = 10; page = 1; string order, sort, oderby; order = sort = oderby = ""; if (null != context.Request.QueryString["rows"]) { pageRows = int.Parse(context.Request.QueryString["rows"].ToString().Trim()); } if (null != context.Request.QueryString["page"]) { page = int.Parse(context.Request.QueryString["page"].ToString().Trim()); } if (null != context.Request.QueryString["sort"]) { order = context.Request.QueryString["sort"].ToString().Trim(); } if (null != context.Request.QueryString["order"]) { sort = context.Request.QueryString["order"].ToString().Trim(); } //=================================================================== //组合查询语句:条件+排序 StringBuilder strWhere = new StringBuilder(); if (tkey != "") { strWhere.AppendFormat("tName like '%{0}%' and ", tkey); } //删除多余的and int startindex = strWhere.ToString().LastIndexOf("and");//获取最后一个and的位置 if (startindex >= 0) { strWhere.Remove(startindex, 3);//删除多余的and关键字 } if (sort != "" && order != "") { //strWhere.AppendFormat(" order by {0} {1}", sort, order);//添加排序 oderby = order + " " + sort; } //DataSet ds = Bnotice.GetList(strWhere.ToString()); //调用不分页的getlist //调用分页的GetList方法 DataSet ds = GetListByPage(strWhere.ToString(), oderby, (page - 1) * pageRows + 1, page * pageRows); int count = GetRecordCount(strWhere.ToString());//获取条数 string strJson = ToJson.Dataset2Json(ds, count);//DataSet数据转化为Json数据 context.Response.Write(strJson);//返回给前台页面 context.Response.End(); } public int GetRecordCount(string strWhere) { SqlHelp sqlx = new SqlHelp(); StringBuilder strSql = new StringBuilder(); strSql.Append("select count(1) FROM Rex_Test"); if (strWhere.Trim() != "") { strSql.Append(" where " + strWhere); } int obj = sqlx.ReturnCount(strSql.ToString()); sqlx.SqlClose(); if (obj<=0) { return 0; } else { return Convert.ToInt32(obj); } } /// <summary> /// 分页获取数据列表 /// </summary> public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex) { SqlHelp sqly = new SqlHelp(); try { StringBuilder strSql = new StringBuilder(); strSql.Append("SELECT * FROM ( "); strSql.Append(" SELECT ROW_NUMBER() OVER ("); if (!string.IsNullOrEmpty(orderby.Trim())) { strSql.Append("order by T." + orderby); } else { strSql.Append("order by ID asc"); } strSql.Append(")AS Row, T.* from Rex_Test T "); if (!string.IsNullOrEmpty(strWhere.Trim())) { strSql.Append(" WHERE " + strWhere); } strSql.Append(" ) TT"); strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex); return sqly.GetDataSet(strSql.ToString()); } finally { sqly.SqlClose(); } } }
ToJson.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; using System.Data; using System.Data.SqlClient; using System.IO; /// <summary> ///ToJson 的摘要说明 /// </summary> public class ToJson { /// <summary> /// DataSet转换成Json格式 /// </summary> /// <paramname="ds">DataSet</param> ///<returns></returns> public static string Dataset2Json(DataSet ds, int total = -1) { StringBuilder json = new StringBuilder(); foreach (DataTable dt in ds.Tables) { //{"total":5,"rows":[ json.Append("{\"total\":"); if (total == -1) { json.Append(dt.Rows.Count); } else { json.Append(total); } json.Append(",\"rows\":["); json.Append(DataTable2Json(dt)); json.Append("]}"); } return json.ToString(); } /// <summary> /// dataTable转换成Json格式 /// </summary> /// <paramname="dt"></param> ///<returns></returns> public static string DataTable2Json(DataTable dt) { StringBuilder jsonBuilder = new StringBuilder(); for (int i = 0; i <dt.Rows.Count; i++) { jsonBuilder.Append("{"); for (int j = 0; j <dt.Columns.Count; j++) { jsonBuilder.Append("\""); jsonBuilder.Append(dt.Columns[j].ColumnName); jsonBuilder.Append("\":\""); jsonBuilder.Append(dt.Rows[i][j].ToString()); jsonBuilder.Append("\","); } if (dt.Columns.Count > 0) { jsonBuilder.Remove(jsonBuilder.Length - 1, 1); } jsonBuilder.Append("},"); } if (dt.Rows.Count > 0) { jsonBuilder.Remove(jsonBuilder.Length - 1, 1); } return jsonBuilder.ToString(); } }
哦,对了,我发现这个Jqurey EasyUI DataGrid的一些功能,比如刷新、分页这些在IE11下,不怎么兼容样,如果有知道解决方法的朋友,希望可以留言,给大家分享一下,谢了。
【Jqurey EasyUI+Asp.net】---DataGrid的增、删、改、查,布布扣,bubuko.com
【Jqurey EasyUI+Asp.net】---DataGrid的增、删、改、查
标签:style blog http java width 数据
原文地址:http://blog.csdn.net/yangmingxing980/article/details/36174519