仅供参考,实现的方法很多。轻喷

第一步:

新建asp.net程序将jquery easyui包拷贝到根目录

根据自己爱好来。

第二步:

新建一个webform页面。

    <link href="JS/themes/default/easyui.css" rel="stylesheet" type="text/css" />
    <link href="JS/themes/icon.css" rel="stylesheet" type="text/css" />
    <script src="JS/jquery-1.8.0.min.js" type="text/javascript"></script>
    <script src="JS/jquery.easyui.min.js" type="text/javascript"></script>

webform页面代码:

  1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="增删改查.WebForm1" %>
  2 <html xmlns="http://www.w3.org/1999/xhtml">
  3 <head runat="server">
  4     <title></title>
  5     <link href="JS/themes/default/easyui.css" rel="stylesheet" type="text/css" />
  6     <link href="JS/themes/icon.css" rel="stylesheet" type="text/css" />
  7     <script src="JS/jquery-1.8.0.min.js" type="text/javascript"></script>
  8     <script src="JS/jquery.easyui.min.js" type="text/javascript"></script>
  9     <script type="text/javascript">
 10         var url; //提交数据的路径
 11         var formId; //当天要提交的Form的编号
 12         var dialogId; //对话框的编号
 13     $(function () {
 14         oks();
 15     });
 16     function oks() {
 17         $("#tab").datagrid({
 18             width: 550,
 19             heigth: 250,
 20             title: "学员信息表",
 21             url: location.href,
 22             idField: 'JSON_id',
 23             frozenColumns: [[
 24                     { field: 'chk', checkbox: true }
 25                 ]],
 26             columns: [[
 27 //                { field: 'JSON_id', title: "id", disply: "none" },
 28                 { field: 'JSON_no', title: '编号', width: 80 },
 29                  { field: 'JSON_name', title: '姓名', width: 100 },
 30                  { field: 'JSON_pwd', title: '密码', width: 80 },
 31                  { field: 'JSON_sex', title: '性别', width: 80 },
 32                   { field: 'JSON_age', title: '年龄', width: 80 },
 33                   { field: 'JSON_address', title: '住址', width: 80 }
 34                 ]],
 35             queryParams: { "action": "query" },
 36             rownumbers: true,
 37             pagination: true,
 38            toolbar:"#tool",
 39            singleSelect: true,
 40            fitColumns: true
 41         });
 42     }
 43     var p = $('#tab').datagrid('getPager');
 44     p.pagination({
 45         beforePageText: '', //页数文本框前显示的汉字           
 46         afterPageText: '页    共 {pages} 页',
 47         displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录'
 48     });
 49     //删除按钮事件
 50     function Del(id) {
 51         $.messager.confirm('提示', '确认删除?', function (r) {
 52             if (r) {
 53                 var selected = "";
 54                 if (id <= 0) {
 55                     $($('#tab').datagrid('getSelections')).each(function () {
 56                         selected += this.JSON_id + ",";
 57                     });
 58                     selected = selected.substr(0, selected.length - 1);
 59                     if (selected == "") {
 60                         $.messager.alert('提示', '请选择要删除的数据!', 'info');
 61                         return;
 62                     }
 63                 }
 64                 else {
 65                     selected = id;
 66                 }
 67                 $.post(location.href, { "action": "del", "chk_select": selected }, function (data) {
 68                     $.messager.alert('提示', data, 'info', function () { $("#tab").datagrid("reload"); });
 69                 });
 70 
 71             }
 72         });
 73         }
 74         function addUser() {
 75             $("#addUser").dialog({
 76                 "title": "添加学员信息",
 77                 width: 500,
 78                 heigth: 450
 79             });
 80             $("#addUser").dialog('open');
 81             $("#addform").form('clear');
 82             url = 'WebForm1.aspx?action=add';
 83             formId = "#addform";
 84             dialogId = "#addUser";
 85         }
 86         function add() {
 87             $(formId).form('submit', {
 88                 url: url,
 89                 onSubmit: function () {
 90                     return $(this).form('validate');
 91                 },
 92                 success: function (data) {
 93                     if (data == 'ok') {
 94                         $.messager.show({
 95                             title: 'success',
 96                             msg: '插入成功!'
 97                         });
 98                         $('#tab').datagrid('reload');
 99                     } else {
100                         $.messager.show({
101                             title: 'Error',
102                             msg: '插入失败!'
103 
104                         });
105                     }
106                     $('#tab').datagrid('reload');
107                 }
108             });
109         }
110         function edittbUser() {
111             $("#editUser").dialog({
112                 "title":"修改信息",
113                 width:500,
114                 heigth:400
115             });
116             var row = $('#tab').datagrid('getSelections');
117             if (row) {
118                 $("#editUser").dialog("open");
119                 $("#editno").val(row[0].JSON_no);
120                 $("#editname").val(row[0].JSON_name);
121                 $("#editpwd").val(row[0].JSON_pwd);
122                 if (row[0].JSON_sex == "") {
123                     $("#editsex").find("option").eq(0).attr("selected", "selected");
124                 } else {
125                     $("#editsex").find("option").eq(1).attr("selected", "selected");
126                 }
127                 $("#editage").val(row[0].JSON_age);
128                 $("#editaddress").val(row[0].JSON_address);
129                 url = "WebForm1.aspx?action=edit&id=" + row[0].JSON_id;
130                 formId = "#editform";
131                 dialogId = "#editUser";
132             } else {
133                 $.messager.alert("提示", "您没有选中任何行!");
134             }
135         }
136         function edit() {
137 
138             $(formId).form('submit', {
139                 url: url,
140                 onSubmit: function () {
141                     return $(this).form('validate');
142                 },
143                 success: function (data) {
144                     if (data == 'ok') {
145                         $.messager.show({
146                             title: 'success',
147                             msg: '修改成功!'
148                         });
149                         $(dialogId).dialog('close');
150                         //$.messager.alert("提示","修改成功~!");
151                         $('#tab').datagrid('reload');
152                     } else {
153                         $.messager.show({
154                             title: 'Error',
155                             msg: '修改失败!'
156                         });
157                     }
158                     $('#tab').datagrid('reload');
159                 }
160             })
161         }
162     </script>
163 </head>
164 <body>
165 <table id="tab"></table>
166     <div id="tool">
167        <table border="0" cellspacing="0" cellpadding="0" width="100%">
168            <tr>
169                <td style=" padding-left:2px">
170                 <a href="#" class="easyui-linkbutton" id="id_add" iconcls="icon-add" onclick="addUser();" plain="true">添加</a>
171                 <a href="#" class="easyui-linkbutton" id="id_edit" iconCls="icon-edit" onclick="edittbUser();" plain="true">修改</a>
172                 <a href="#" class="easyui-linkbutton" id="id_cancel " onclick="Del(0);return false;" iconcls="icon-cancel" plain="true">删除</a>
173             </td>
174 
175            </tr>
176        </table>
177     </div>
178     <div id="addUser" class="easyui-dialog" closed="true" buttons="#addusers" style="padding:10px 20px">
179     <form id="addform" method="post">
180             <table class="align-center">
181                 <tr>
182                     <td>编号</td>
183                     <td>
184                         <input type="text" class="easyui-validatebox" data-options="required:true" name="no"/>
185                     </td>
186                 </tr>
187                 <tr>
188                     <td>姓名</td>
189                     <td> <input type="text" class="easyui-validatebox" data-options="required:true" name="name"/></td>
190                 </tr>
191                    <tr>
192                     <td>密码</td>
193                     <td> <input type="password" class="easyui-validatebox" data-options="required:true" name="pwd"/></td>
194                 </tr>
195                 <tr>
196                    <td>性别</td>
197                    <td>
198                     <select name="sex">
199                         <option value="1">男</option>
200                         <option value="0">女</option>
201                     </select>
202                    </td>
203                 </tr>
204                 <tr>
205                     <td>年龄</td>
206                     <td> <input type="text" class="easyui-validatebox" data-options="required:true" name="age"/></td>
207                 </tr>
208                 <tr>
209                     <td>住址</td>
210                     <td> <input type="text" class="easyui-validatebox" data-options="required:true" name="address"/></td>
211                 </tr>
212             </table>
213     </form>
214     </div>
215     <div id="addusers">
216         <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="add()">保存</a>
217        <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#addUser').dialog('close')">关闭</a>
218     </div>
219 
220     <div id="editUser" class="easyui-dialog" closed="true" buttons="#editusers" style="padding:10px 20px">
221     <form id="editform" method="post">
222             <table class="align-center">
223                 <tr>
224                     <td>编号</td>
225                     <td>
226                         <input type="text" id="editno" class="easyui-validatebox" data-options="required:true" name="no"/>
227                     </td>
228                 </tr>
229                 <tr>
230                     <td>姓名</td>
231                     <td> <input type="text" id="editname" class="easyui-validatebox" data-options="required:true" name="name"/></td>
232                 </tr>
233                    <tr>
234                     <td>密码</td>
235                     <td> <input type="password" id="editpwd" class="easyui-validatebox" data-options="required:true" name="pwd"/></td>
236                 </tr>
237                 <tr>
238                    <td>性别</td>
239                    <td>
240                     <select name="editsex" id="editsex">
241                         <option value="1">男</option>
242                         <option value="0">女</option>
243                     </select>
244                    </td>
245                 </tr>
246                 <tr>
247                     <td>年龄</td>
248                     <td> <input type="text" id="editage" class="easyui-validatebox" data-options="required:true" name="age"/></td>
249                 </tr>
250                 <tr>
251                     <td>住址</td>
252                     <td> <input type="text" id="editaddress" class="easyui-validatebox" data-options="required:true" name="address"/></td>
253                 </tr>
254             </table>
255     </form>
256     </div>
257      <div id="editusers">
258         <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="edit()">保存</a>
259        <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#editUser').dialog('close')">关闭</a>
260     </div>
261 </body>
262 </html>

第三步:

webform后台代码

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Web.UI;
  6 using System.Web.UI.WebControls;
  7 using System.Data;
  8 using System.Text;
  9 
 10 namespace 增删改查
 11 {
 12     public partial class WebForm1 : System.Web.UI.Page
 13     {
 14         protected void Page_Load(object sender, EventArgs e)
 15         {
 16             if (Request["action"] != null)
 17             {
 18                 string action = Request["action"].ToString();
 19                 switch (action)
 20                 {
 21                     case "query":
 22                         Query();
 23                         break;
 24                     case "del":
 25                         Del();
 26                         break;
 27                     case "add":
 28                         Add();
 29                         break;
 30                     case "edit":
 31                         Edit();
 32                         break;
 33                 }
 34             }
 35         }
 36         //显示
 37         private void Query()
 38         {
 39             string str = string.Empty;
 40             string sql = string.Empty;
 41             string rows = Request["rows"].ToString();  //获取datagrid传来的行数
 42             string page = Request["page"].ToString(); //获取datagrid传来的页码 当前页
 43             StringBuilder sb = new StringBuilder();
 44             sb.AppendFormat(" SELECT TOP {0} * FROM ( ",rows);
 45             sb.Append(" SELECT ROW_NUMBER() OVER (ORDER BY id) AS  ");
 46             sb.Append(" RowNumber,* FROM stu) A ");
 47              sql = sb.ToString();
 48              sql+=string.Format(" WHERE RowNumber > {0}*({1}-1) ",rows,page);
 49              DataTable dt = SqlHelper.GetTable(sql);
 50              DataTable dt2 = SqlHelper.GetTable("select * from stu");
 51             str = JSONHelper.CreateJsonParameters(dt, true, dt2.Rows.Count);
 52             Response.Write(str);
 53             Response.End();
 54         }
 55 
 56         private void Del()
 57         {
 58             string str = "删除失败";
 59             string selectid = Request["chk_select"] != "" ? Request["chk_select"].ToString() : "";
 60             if (selectid != string.Empty && selectid != "0")
 61             {
 62                 
 63                 int num=SqlHelper.DelData("stu",selectid);
 64                 if(num>0)
 65                 {
 66                     str = string.Format("删除成功,本次共删除{0}条", num.ToString());
 67                 }else
 68                 {
 69                     str="删除失败";
 70                 }
 71                 Response.Write(str);
 72                 Response.End();
 73             }
 74         }
 75 
 76         private void Add()
 77         {
 78             string no = Request["no"].ToString();
 79             string name = Request["name"].ToString();
 80             string pwd = Request["pwd"].ToString();
 81             string sex = Request["sex"].ToString()=="1"?"":"";
 82             int age = int.Parse(Request["age"].ToString());
 83             string address = Request["address"].ToString();
 84             string sql = string.Format("insert into stu values('{0}','{1}','{2}','{3}',{4},'{5}')",no,name,pwd,sex,age,address);
 85             int count = 0;
 86             count = SqlHelper.ExeNonQuery(sql, CommandType.Text, null) ? 1 : 0;
 87             if (count > 0)
 88             {
 89                 Response.Write("ok");
 90                 Response.End();
 91             }
 92             else
 93             {
 94                 Response.Write("no");
 95                 Response.End();
 96             }
 97         }
 98         private void Edit()
 99         {
100             int id = int.Parse(Request["id"].ToString());
101             string no = Request["no"].ToString();
102             string name = Request["name"].ToString();
103             string pwd = Request["pwd"].ToString();
104             string sex = Request["editsex"].ToString() == "1" ? "" : "";
105             int age = int.Parse(Request["age"].ToString());
106             string address = Request["address"].ToString();
107             int count = 0;
108             string sql = string.Format("update stu set no='{0}',name='{1}',pwd='{2}',sex='{3}',age={4},address='{5}' where id={6}",no,name,pwd,sex,age,address,id);
109             count = SqlHelper.ExeNonQuery(sql, CommandType.Text, null) ? 1 : 0;
110             if (count > 0)
111             {
112                 Response.Write("ok");
113                 Response.End();
114             }
115             else
116             {
117                 Response.Write("no");
118                 Response.End();
119             }
120         }
121        
122     }
123 }

sqlhelper:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Data.SqlClient;
  6 using System.Data;
  7 using System.Configuration;
  8 
  9     public class SqlHelper
 10     {
 11         /// <summary>
 12         /// 数据连接字符串
 13         /// </summary>
 14         public static readonly string conString = ConfigurationManager.ConnectionStrings["sqlCon"].ConnectionString;
 15         //增删改
 16         public static bool ExeNonQuery(string sql, CommandType type, params SqlParameter[] lists)
 17         {
 18             bool bFlag = false;
 19             using (SqlConnection con = new SqlConnection(conString))
 20             {
 21                 SqlCommand cmd = new SqlCommand();
 22                 cmd.Connection = con;
 23                 cmd.CommandText = sql;
 24                 cmd.CommandType = type;
 25                 if (lists!=null)
 26                 {
 27                     foreach (SqlParameter p in lists)
 28                     {
 29                         cmd.Parameters.Add(p);
 30                     }
 31                 }
 32                 try
 33                 {
 34                     if (con.State == ConnectionState.Closed)
 35                     {
 36                         con.Open();
 37                     }
 38                     int result = cmd.ExecuteNonQuery();
 39                     if (result > 0)
 40                     {
 41                         bFlag = true;
 42                     }
 43 
 44                 }
 45                 catch { ;}
 46             }
 47             return bFlag;
 48         }
 49 
 50         //查.读
 51         public static SqlDataReader ExeDataReader(string sql, CommandType type, params SqlParameter[] lists)
 52         {
 53             SqlConnection con = new SqlConnection(conString);
 54             SqlCommand cmd = new SqlCommand();
 55             cmd.Connection = con;
 56             cmd.CommandText = sql;
 57             cmd.CommandType = type;
 58 
 59             if (con.State == ConnectionState.Closed)
 60             {
 61                 con.Open();
 62             }
 63 
 64             if (lists!=null)
 65             {
 66                 foreach (SqlParameter p in lists)
 67                 {
 68                     cmd.Parameters.Add(p);
 69                 }
 70             }
 71 
 72             SqlDataReader reader = cmd.ExecuteReader();
 73 
 74             return reader;
 75         }
 76 
 77         //返回单个值
 78         public static object GetScalar(string sql, CommandType type, params SqlParameter[] lists)
 79         {
 80             object returnValue = null;
 81             using (SqlConnection con = new SqlConnection(conString))
 82             {
 83                 SqlCommand cmd = new SqlCommand();
 84                 cmd.Connection = con;
 85                 cmd.CommandText = sql;
 86                 cmd.CommandType = type;
 87                 if (lists!=null)
 88                 {
 89                     foreach (SqlParameter p in lists)
 90                     {
 91                         cmd.Parameters.Add(p);
 92                     }
 93                 }
 94                 try
 95                 {
 96                     if (con.State == ConnectionState.Closed)
 97                     {
 98                         con.Open();
 99                     }
100                     returnValue = cmd.ExecuteScalar();
101 
102                 }
103                 catch { ; }
104             }
105             return returnValue;
106         }
107 
108         //事务
109         public static bool ExeNonQueryTran(List<SqlCommand> list)
110         {
111             bool flag = true;
112             SqlTransaction tran = null;
113             using (SqlConnection con = new SqlConnection(conString))
114             {
115                 try
116                 {
117                     if (con.State == ConnectionState.Closed)
118                     {
119                         con.Open();
120                         tran = con.BeginTransaction();
121                         foreach (SqlCommand com in list)
122                         {
123                             com.Connection = con;
124                             com.Transaction = tran;
125                             com.ExecuteNonQuery();
126                         }
127                         tran.Commit();
128                     }
129                 }
130                 catch (Exception ex)
131                 {
132                     Console.Write(ex.Message);
133                     tran.Rollback();
134                     flag = false;
135                 }
136             }
137             return flag;
138         }
139         //返回DataTable
140         public static DataTable GetTable(string sql)
141         {
142             SqlConnection conn = new SqlConnection(conString);
143             SqlDataAdapter da = new SqlDataAdapter(sql, conn);
144             DataTable table = new DataTable();
145             da.Fill(table);
146             return table;
147         }
148         public static DataTable GetDataByPager(string tbname, string fieldkey, int pagecurrent, int pagesize, string fieldshow, string fieldorder, string wherestring, ref int pagecount)
149         {
150             SqlParameter[] parameters = {
151                 new SqlParameter("@tbname",   SqlDbType.VarChar, 100),
152                 new SqlParameter("@FieldKey", SqlDbType.VarChar, 100),
153                 new SqlParameter("@PageCurrent", SqlDbType.Int),
154                 new SqlParameter("@PageSize", SqlDbType.Int),
155                 new SqlParameter("@FieldShow", SqlDbType.VarChar, 200),
156                 new SqlParameter("@FieldOrder", SqlDbType.VarChar, 200),
157                 new SqlParameter("@WhereString", SqlDbType.VarChar, 500),
158                 new SqlParameter("@RecordCount", SqlDbType.Int),
159             };
160             parameters[0].Value = tbname;
161             parameters[1].Value = fieldkey;
162             parameters[2].Value = pagecurrent;
163             parameters[3].Value = pagesize;
164             parameters[4].Value = fieldshow;
165             parameters[5].Value = fieldorder;
166             parameters[6].Value = wherestring;
167             parameters[7].Direction = ParameterDirection.Output;
168             DataTable dt = ExecuteQuery("sp_get_data", parameters).Tables[0];
169             pagecount = Convert.ToInt32(parameters[7].Value);
170             return dt;
171         }
172         /// <summary>
173         /// 执行有参数的查询类存储过程
174         /// </summary>
175         /// <param name="pstrStoreProcedure">存储过程名</param>
176         /// <param name="pParms">存储过程的参数数组</param>
177         /// <returns>查询得到的结果集</returns>
178         public static DataSet ExecuteQuery(string pstrStoreProcedure, SqlParameter[] pParms)
179         {
180 
181 
182             DataSet dsResult = new DataSet();
183             SqlDataAdapter sda = new SqlDataAdapter();
184             SqlConnection con=new SqlConnection(conString);
185             SqlCommand cmd;
186             int intCounter;
187             try
188             {
189                 if (con.State != ConnectionState.Open)
190                     con.Open();
191                 cmd = new SqlCommand();
192                 cmd.Connection = con;
193                 cmd.CommandType = CommandType.StoredProcedure;
194                 cmd.CommandText = pstrStoreProcedure;
195                 if (pParms != null)
196                 {
197                     for (intCounter = 0; intCounter < pParms.GetLength(0); intCounter++)
198                     {
199                         cmd.Parameters.Add(pParms[intCounter]);
200                     }
201                 }
202                 sda.SelectCommand = cmd;
203                 sda.Fill(dsResult);
204 
205 
206             }
207             catch (SqlException ex)
208             {
209                 throw new Exception(ex.Message );
210             }
211             finally
212             {
213                 //清空关闭操作
214                 sda.Dispose();
215                 con.Close();
216                 con.Dispose();
217 
218             }
219             return dsResult;
220         }
221         /// <summary>
222         /// 此分页存储过程直接用皱建的,没修改 大家可以用自己的
223         /// </summary>
224         /// <param name="tableName">表名</param>
225         /// <param name="getFields">需要返回的列</param>
226         /// <param name="orderName">排序的字段名</param>
227         /// <param name="pageSize">页尺寸</param>
228         /// <param name="pageIndex">页码</param>
229         /// <param name="isGetCount">返回记录总数,非 0 值则返回</param>
230         /// <param name="orderType">设置排序类型,0表示升序非0降序</param>
231         /// <param name="strWhere"></param>
232         /// <returns></returns>
233         //public static DataSet GetList(string tableName, string getFields, string orderName, int pageSize, int pageIndex, bool isGetCount, bool orderType, string strWhere)
234         //{
235         //    SqlParameter[] parameters = {
236         //            new SqlParameter("@tblName", SqlDbType.VarChar, 255),
237         //            new SqlParameter("@strGetFields", SqlDbType.VarChar, 1000),
238         //            new SqlParameter("@fldName", SqlDbType.VarChar, 255),
239         //          new SqlParameter("@PageSize", SqlDbType.Int),
240         //       new SqlParameter("@PageIndex", SqlDbType.Int),
241         //        new SqlParameter("@doCount", SqlDbType.Bit),
242         //            new SqlParameter("@OrderType", SqlDbType.Bit),
243         //            new SqlParameter("@strWhere", SqlDbType.VarChar, 1500)            
244         //                             };
245         //    parameters[0].Value = tableName;
246         //    parameters[1].Value = getFields;
247         //    parameters[2].Value = orderName;
248         //    parameters[3].Value = pageSize;
249         //    parameters[4].Value = pageIndex;
250         //    parameters[5].Value = isGetCount ? 1 : 0;
251         //    parameters[6].Value = orderType ? 1 : 0;
252         //    parameters[7].Value = strWhere;
253         //    return SqlHelper.RunProcedure("pro_pageList", parameters, "ds");
254         //}
255         //public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
256         //{
257         //    using (SqlConnection connection = new SqlConnection(conString))
258         //    {
259         //        DataSet dataSet = new DataSet();
260         //        connection.Open();
261         //        new SqlDataAdapter { SelectCommand = BuildQueryCommand(connection, storedProcName, parameters) }.Fill(dataSet, tableName);
262         //        connection.Close();
263         //        return dataSet;
264         //    }
265         //}
266         /// <summary>
267         /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
268         /// </summary>
269         /// <param name="connection">数据库连接</param>
270         /// <param name="storedProcName">存储过程名</param>
271         /// <param name="parameters">存储过程参数</param>
272         /// <returns>SqlCommand</returns>
273         private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
274         {
275             SqlCommand command = new SqlCommand(storedProcName, connection)
276             {
277                 CommandType = CommandType.StoredProcedure
278             };
279             foreach (SqlParameter parameter in parameters)
280             {
281                 if (parameter != null)
282                 {
283                     if (((parameter.Direction == ParameterDirection.InputOutput) || (parameter.Direction == ParameterDirection.Input)) && (parameter.Value == null))
284                     {
285                         parameter.Value = DBNull.Value;
286                     }
287                     command.Parameters.Add(parameter);
288                 }
289             }
290             return command;
291         }
292         //根据表名和主键id来进行删除
293         public static int DelData(string tabName, string ID)
294         {
295             if (ID != string.Empty && ID != "0")
296             {
297                 string sql = string.Format("delete from {0}  WHERE (ID IN ({1}))", tabName, ID);
298                 int delNum = ExecuteSql(sql);
299                 return delNum;
300             }
301             return 0;
302         }
303         //增删改返回执行条数
304         public static int ExecuteSql(string SQLString)
305         {
306             int num2;
307             using (SqlConnection connection = new SqlConnection(conString))
308             {
309                 SqlCommand command = new SqlCommand(SQLString, connection);
310                 try
311                 {
312                     connection.Open();
313                     num2 = command.ExecuteNonQuery();
314                 }
315                 catch (SqlException exception)
316                 {
317                     connection.Close();
318                     throw exception;
319                 }
320                 finally
321                 {
322                     if (command != null)
323                     {
324                         command.Dispose();
325                     }
326                 }
327             }
328             return num2;
329         }
330     }

JSONHelper:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Data;
  6 
  7 using System.Text;
  8 using System.Web.Script.Serialization;
  9 
 10 /// <summary>
 11 ///JsonHelper 的摘要说明
 12 /// </summary>
 13 public class JSONHelper
 14 {
 15     private static List<Dictionary<string, object>> DataTableToList(DataTable table)
 16     {
 17         List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
 18 
 19         foreach (DataRow row in table.Rows)
 20         {
 21             Dictionary<string, object> dic = new Dictionary<string, object>();
 22             foreach (DataColumn column in table.Columns)
 23             {
 24                 dic.Add(column.ColumnName,row[column.ColumnName]);
 25             }
 26             list.Add(dic);
 27         }
 28 
 29         return list;
 30     }
 31 
 32     public static string ObjectToJson(object obj)
 33     {
 34         JavaScriptSerializer jss = new JavaScriptSerializer();
 35         return jss.Serialize(obj);
 36     }
 37 
 38     public static string DataTableToJson(DataTable table)
 39     {
 40         return ObjectToJson(DataTableToList(table));
 41     }
 42 
 43     /// <summary>
 44     /// 通过拼字符串将DataTable转为Json
 45     /// </summary>
 46     /// <param name="table"></param>
 47     /// <returns></returns>
 48     public static string DataTableToJsonEx(DataTable table)
 49     {
 50         string JsonName = "DataTable";
 51         StringBuilder Json = new StringBuilder("{\"" + JsonName + "\":[");
 52         if (table.Rows.Count > 0)
 53         {
 54             foreach (DataRow row in table.Rows)
 55             {
 56                 Json.Append("{");
 57                 foreach (DataColumn column in table.Columns)
 58                 {
 59                     Json.Append("\"" + column.ColumnName + "\":\"" + row[column.ColumnName].ToString() + "\",");
 60                 }
 61                 Json.Remove(Json.Length - 1, 1);
 62                 Json.Append("},");
 63             }
 64             Json.Remove(Json.Length - 1, 1);
 65         }
 66         Json.Append("]}");
 67 
 68         return Json.ToString();
 69     }
 70     public static string CreateJsonParameters(DataTable dt, bool displayCount, int totalcount)
 71     {
 72         StringBuilder JsonString = new StringBuilder();
 73         //Exception Handling        
 74         if (dt != null)
 75         {
 76             JsonString.Append("{ ");
 77             if (displayCount)
 78             {
 79                 JsonString.Append("\"total\":");
 80                 JsonString.Append(totalcount);
 81                 JsonString.Append(",");
 82             }
 83             JsonString.Append("\"rows\":[ ");
 84             for (int i = 0; i < dt.Rows.Count; i++)
 85             {
 86                 JsonString.Append("{ ");
 87                 for (int j = 0; j < dt.Columns.Count; j++)
 88                 {
 89                     if (j < dt.Columns.Count - 1)
 90                     {
 91                         //if (dt.Rows[i][j] == DBNull.Value) continue;
 92                         if (dt.Columns[j].DataType == typeof(bool))
 93                         {
 94                             JsonString.Append("\"JSON_" + dt.Columns[j].ColumnName.ToLower() + "\":" +
 95                                               dt.Rows[i][j].ToString().ToLower() + ",");
 96                         }
 97                         else if (dt.Columns[j].DataType == typeof(string))
 98                         {
 99                             JsonString.Append("\"JSON_" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" +
100                                               dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\",");
101                         }
102                         else
103                         {
104                             JsonString.Append("\"JSON_" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\",");
105                         }
106                     }
107                     else if (j == dt.Columns.Count - 1)
108                     {
109                         //if (dt.Rows[i][j] == DBNull.Value) continue;
110                         if (dt.Columns[j].DataType == typeof(bool))
111                         {
112                             JsonString.Append("\"JSON_" + dt.Columns[j].ColumnName.ToLower() + "\":" +
113                                               dt.Rows[i][j].ToString().ToLower());
114                         }
115                         else if (dt.Columns[j].DataType == typeof(string))
116                         {
117                             JsonString.Append("\"JSON_" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" +
118                                               dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\"");
119                         }
120                         else
121                         {
122                             JsonString.Append("\"JSON_" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\"");
123                         }
124                     }
125                 }
126                 /*end Of String*/
127                 if (i == dt.Rows.Count - 1)
128                 {
129                     JsonString.Append("} ");
130                 }
131                 else
132                 {
133                     JsonString.Append("}, ");
134                 }
135             }
136             JsonString.Append("]");
137             JsonString.Append("}");
138             return JsonString.ToString().Replace("\n", "");
139         }
140         else
141         {
142             return null;
143         }
144     }
145     public static string DtToSON2(DataTable dt, string page, string total)
146     {
147         StringBuilder jsonString = new StringBuilder();
148         jsonString.AppendLine("{");
149         jsonString.AppendFormat("page: {0},\n", page);
150         jsonString.AppendFormat("total: {0},\n", total);
151         jsonString.AppendLine("rows: [");
152         for (int i = 0; i < dt.Rows.Count; i++)
153         {
154             jsonString.Append("{");
155             jsonString.AppendFormat("id:'{0}',cell:[", dt.Rows[i][0].ToString());
156             for (int j = 0; j < dt.Columns.Count; j++)
157             {
158                 if (j == dt.Columns.Count - 1)
159                 {
160                     jsonString.AppendFormat("'{0}'", dt.Rows[i][j].ToString());
161                 }
162                 else
163                 {
164                     jsonString.AppendFormat("'{0}',", dt.Rows[i][j].ToString());
165                 }
166                 if (j == dt.Columns.Count - 1)
167                 {
168                     jsonString.AppendFormat(",'{0}'", "<input type=\"button\" value=\"查看\" id=\"sss\" onclick=\"sss(" + dt.Rows[i][0].ToString() + ")\" />");
169                 }
170             }
171             jsonString.Append("]");
172             if (i == dt.Rows.Count - 1)
173             {
174                 jsonString.AppendLine("}");
175             }
176             else
177             {
178                 jsonString.AppendLine("},");
179             }
180         }
181         jsonString.Append("]");
182         jsonString.AppendLine("}");
183         return jsonString.ToString();
184     }
185 }

数据库表字段: