Repeater增删改查(内嵌checkbox)版本
基础知识比较重要为了巩固以前所学习的,在此篇博客中主要描述了下以前repeater中常用的一些增删改查,更主要的是为了利用Jquery完成全选批量删除的功能,代码十分简单也没使用存储过程,欢迎提出您的见解和意见谢谢~此文只为分享学习~
前台Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="RepeaterDemo._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 id="Head1" runat="server">
<title>Repeater增删改查实例(内嵌Checkbox版)</title>
<style type="text/css">
tr td span
{
font-family: @宋体, Arial;
font-size: small;
color: Gray;
}
tr td
{
width: 100px;
text-align: center;
}
</style>
<%--<script src="Jquery/jquery-1.4.min.js" type="text/javascript" language="javascript"></script>--%>
<script src="Jquery/jquery-1.4.2-vsdoc.js" type="text/javascript" language="javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("tr[id='repeaterTr']").each(function() {
$(this).mouseover(function() {
$(this).css("background-color", "#77DDFF");
})
$(this).mouseout(function() {
$(this).css("background-color", "#FFFFFF");
});
});
//toggle用于切换2个函数
$("#btnCheckAll").toggle(function() {
if ($("#btnCheckAll").html() == "全选") {
$("#btnCheckAll").click(function() {
$(this).html("反选");
$("input[name='product']").each(function() {
if ($(this).attr("checked", false)) {
$(this).attr("checked", true);
}
})
})
}
}, function() {
if ($("#btnCheckAll").html() == "反选") {
$("#btnCheckAll").click(function() {
$(this).html("全选");
$("input[name='product']").each(function() {
if ($(this).attr("checked", true)) {
$(this).attr("checked", false);
}
})
})
}
})
})
function TransformIDs() {
var checkedArray = new Array();
$("input[name='product']").each(function() {
if ($(this).attr("checked") == true) {
checkedArray.push($(this).val());
}
})
$("#checkedIds").get(0).value = checkedArray.join(';');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div align="center">
repeater实例</div>
<input type="hidden" runat="server" id="checkedIds" />
<table border="1" style="width: 600px; border-style: solid; border-collapse: collapse"
align="center">
<tr>
<td>
<button id="btnCheckAll" type="button" value="checkAll" style="border-style: solid">
全选</button>
</td>
<td>
<span>序号</span>
</td>
<td>
<span>商品名</span>
</td>
<td>
<span>单价</span>
</td>
<td>
<span>简介</span>
</td>
<td>
<span>订购日期</span>
</td>
<td>
<span>操作</span>
</td>
</tr>
<asp:Repeater ID="rpProduct" runat="server" OnItemCommand="rpProduct_ItemCommand">
<ItemTemplate>
<tr id="repeaterTr">
<td>
<input type="checkbox" id="chkDelete" name="product" value='<%#Eval("ProductID") %>' />
</td>
<td>
<%#Container.ItemIndex + 1%>
</td>
<td>
<%#Eval("ProductName")%>
</td>
<td>
<%#Eval("UnitPrice", "{0:C}")%>
</td>
<td>
<%#Eval("Description")%>
</td>
<td>
<%#Eval("CreateTime")%>
</td>
<td>
<asp:LinkButton ID="lkbtnEdit" runat="server" Text="编辑" ToolTip="编辑" CommandName="Edit"
CommandArgument='<%#Eval("ProductID") %>' Font-Size="Small"></asp:LinkButton>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
<table border="1" style="width: 600px; border-style: solid; border-collapse: collapse"
align="center">
<tr>
<td align="center">
<span>商品名</span>
</td>
<td align="center">
<span>单价</span>
</td>
<td align="center">
<span>简介</span>
</td>
</tr>
<tr>
<td style="width: 200px" align="center">
<asp:TextBox ID="txtProductName" runat="server" Width="200px"></asp:TextBox>
</td>
<td style="width: 200px" align="center">
<asp:TextBox ID="txtUnitPrice" runat="server" Width="200px"></asp:TextBox>
</td>
<td style="width: 200px" align="center">
<asp:TextBox ID="txtDescription" runat="server" Width="200px"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="3" align="center">
<asp:Button ID="btnAdd" runat="server" Text="添加" OnClick="btnAdd_Click" BorderStyle="Solid" />
<asp:Button ID="btnDelete" runat="server" Text="删除" OnClick="btnDelete_Click" BorderStyle="Solid"
OnClientClick="TransformIDs()" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
后台Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Text.RegularExpressions;
namespace RepeaterDemo
{
/// <summary>
/// 简化例子没有分层与使用存储过程
/// </summary>
public partial class _Default : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RepeatDataBind();
}
}
/// <summary>
/// repeater控件数据绑定
/// </summary>
private void RepeatDataBind()
{
rpProduct.DataSource = GetProduct().Tables["Product"];
rpProduct.DataBind();
}
/// <summary>
/// 添加新商品记录
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnAdd_Click(object sender, EventArgs e)
{
bool flag = InsertNewProduct();
if (flag)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('添加成功!')</script>");
RepeatDataBind();
ClearData(this.Page.Controls);
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('添加失败发生异常!')</script>");
return;
}
}
/// <summary>
/// 返回结果
/// </summary>
/// <returns></returns>
private DataSet GetProduct()
{
string connectionString = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Product", conn);
DataSet ds = new DataSet();
da.Fill(ds, "Product");
return ds;
}
/// <summary>
/// 插入新记录
/// </summary>
/// <returns></returns>
private bool InsertNewProduct()
{
bool flag = false;
Regex regx = new Regex(@"^/d+$");
if (!regx.IsMatch(txtUnitPrice.Text.Trim()))
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('您输入的不是数字请重新输入!')</script>");
return false;
}
string connectionString = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(@"INSERT INTO Product (ProductName, UnitPrice, Description, CreateTime) VALUES (@ProductName, @UnitPrice, @Description, @CreateTime)", conn);
cmd.Parameters.Add("@ProductName", SqlDbType.NVarChar, 1000).Value = txtProductName.Text.Trim();
cmd.Parameters.Add("@UnitPrice", SqlDbType.Decimal, int.MaxValue).Value = Convert.ToDecimal(txtUnitPrice.Text.Trim());
cmd.Parameters.Add("@Description", SqlDbType.Text, int.MaxValue).Value = txtDescription.Text.Trim();
cmd.Parameters.Add("@CreateTime", SqlDbType.DateTime, int.MaxValue).Value = DateTime.Now;
try
{
conn.Open();
int result = cmd.ExecuteNonQuery();
flag = result == 0 ? false : true;
}
catch (Exception)
{
}
finally
{
conn.Close();
}
return flag;
}
/// <summary>
/// 删除记录
/// </summary>
/// <param name="productID"></param>
/// <returns></returns>
private bool DeleteProduct(int productID)
{
bool flag = false;
string connectionString = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(@"DELETE FROM Product WHERE ProductID = @ProductID", conn);
cmd.Parameters.Add("@ProductID", SqlDbType.Int, int.MaxValue).Value = productID;
try
{
conn.Open();
int result = cmd.ExecuteNonQuery();
flag = result == 0 ? false : true;
}
catch (Exception)
{
}
finally
{
conn.Close();
}
return flag;
}
/// <summary>
/// 批量删除可以用 DELETE FROM TestTable WHERE ID IN (1, 3, 54, 68) --sql2005下运行通过
/// 批量插入可以用
/// sql写法: INSERT INTO TestTable SELECT 1, 'abc' UNION SELECT 2, 'bcd' UNION SELECT 3, 'cde' --TestTable表没有主键,ID不是主键
/// oracle写法: INSERT INTO TestTable SELECT 1, 'abc' From daul UNION SELECT 2, 'bcd' From daul --TestTable表没有主键,ID不是主键
/// </summary>
/// <param name="productIDs"></param>
/// <returns></returns>
private bool DeleteProduct(string[] productIDs)
{
bool flag = false;
string delSqlIds = string.Empty;
string connectionString = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
for (int i = 0; i < productIDs.Length; i++)
{
delSqlIds += productIDs[i] + ", ";
}
delSqlIds = delSqlIds.Substring(0, delSqlIds.LastIndexOf(","));
SqlCommand cmd = new SqlCommand(@"DELETE FROM Product WHERE ProductID in (" + delSqlIds + ")", conn);
try
{
conn.Open();
int result = cmd.ExecuteNonQuery();
flag = result == 0 ? false : true;
}
catch (Exception)
{
}
finally
{
conn.Close();
}
return flag;
}
protected void rpProduct_ItemCommand(object source, RepeaterCommandEventArgs e)
{
string commandName = e.CommandName;
int productID = Convert.ToInt32(e.CommandArgument);
if (commandName == "Edit")
{
Response.Redirect("EditProduct.aspx?Id=" + productID);
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
string[] ids = checkedIds.Value.Split(';');
bool flag = DeleteProduct(ids);
if (flag)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('删除成功!')</script>");
RepeatDataBind();
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('删除失败发生异常!')</script>");
return;
}
}
}
}
前台 EditProduct.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EditProduct.aspx.cs" Inherits="RepeaterDemo.EditProduct" %>
<%@ Register Src="EditProductCtrl.ascx" TagName="EditProductCtrl" TagPrefix="uc1" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<table border="1" style="width: 600px; border-style: solid; border-collapse: collapse"
align="center">
<tr>
<td align="center">
<uc1:EditProductCtrl ID="EditProductCtrl1" runat="server" />
</td>
</tr>
<tr>
<td colspan="3" align="center">
<asp:Button ID="btnEdit" runat="server" Text="编辑" OnClick="btnEdit_Click" BorderStyle="Solid" />
<asp:Button ID="btnReturn" runat="server" Text="返回" OnClick="btnReturn_Click" BorderStyle="Solid" />
</td>
</tr>
</table>
</form>
</body>
</html>
后台 EditProduct.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using Model;
using System.Text.RegularExpressions;
namespace RepeaterDemo
{
public partial class EditProduct : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int productID = int.Parse(Request.QueryString["Id"]);
PageInit(productID);
ViewState["ProductID"] = productID;
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
int productID = Convert.ToInt32(ViewState["ProductID"]);
bool flag = EditCurrentProduct(productID);
if (flag)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('更新成功!');document.location.href='Default.aspx'< /script>");
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('更新失败发生异常!');document.location.href='Default.aspx'& lt;/script>");
return;
}
}
protected void btnReturn_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
private void PageInit(int productID)
{
Product currentProduct = GetCurrentProduct(productID);
this.EditProductCtrl1.ProductName = currentProduct.ProductName;
this.EditProductCtrl1.UnitPrice = currentProduct.UnitPrice;
this.EditProductCtrl1.Description = currentProduct.Decription;
}
/// <summary>
/// 取得当前修改对象
/// </summary>
/// <returns></returns>
private Product GetCurrentProduct(int productID)
{
string connectionString = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Product WHERE ProductID = @ProductID", conn);
da.SelectCommand.Parameters.Add("@ProductID", SqlDbType.Int, int.MaxValue).Value = productID;
DataSet ds = new DataSet();
da.Fill(ds, "Product");
Product currentProduct = new Product();
currentProduct.ProductID = ds.Tables["Product"].Rows[0]["ProductID"] == null ? 0 : Convert.ToInt32(ds.Tables["Product"].Rows[0]["ProductID"]);
currentProduct.ProductName = ds.Tables["Product"].Rows[0]["ProductName"] == null ? string.Empty : (ds.Tables["Product"].Rows[0]["ProductName"]).ToString();
currentProduct.UnitPrice = ds.Tables["Product"].Rows[0]["UnitPrice"] == null ? 0 : Convert.ToDecimal(ds.Tables["Product"].Rows[0]["UnitPrice"]);
currentProduct.Decription = ds.Tables["Product"].Rows[0]["Description"] == null ? string.Empty : (ds.Tables["Product"].Rows[0]["Description"]).ToString();
currentProduct.CreateTime = ds.Tables["Product"].Rows[0]["CreateTime"] == null ? DateTime.Now : Convert.ToDateTime(ds.Tables["Product"].Rows[0]["CreateTime"]);
return currentProduct;
}
/// <summary>
/// 更新当前对象
/// </summary>
/// <param name="productID"></param>
/// <returns></returns>
private bool EditCurrentProduct(int productID)
{
bool flag = false;
if (this.EditProductCtrl1.UnitPrice == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('您输入的不是数字请重新输入,格式不正确!')</script>");
return false;
}
string connectionString = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(@"UPDATE Product SET ProductName = @ProductName, UnitPrice = @UnitPrice, Description = @Description WHERE ProductID = @ProductID", conn);
cmd.Parameters.Add("@ProductName", SqlDbType.NVarChar, 1000).Value = this.EditProductCtrl1.ProductName;
cmd.Parameters.Add("@UnitPrice", SqlDbType.Decimal, int.MaxValue).Value = this.EditProductCtrl1.UnitPrice;
cmd.Parameters.Add("@Description", SqlDbType.Text, int.MaxValue).Value = this.EditProductCtrl1.Description;
cmd.Parameters.Add("@ProductID", SqlDbType.Int, int.MaxValue).Value = productID;
try
{
conn.Open();
int result = cmd.ExecuteNonQuery();
flag = result == 0 ? false : true;
}
catch (Exception)
{
}
finally
{
conn.Close();
}
return flag;
}
}
}
用户控件前台 EditProductCtrl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="EditProductCtrl.ascx.cs"
Inherits="RepeaterDemo.EditProductCtrl" %>
<table border="1" style="width: 600px; border-style: solid; border-collapse: collapse"
align="center">
<tr>
<td align="center">
<span>商品名</span>
</td>
<td align="center">
<span>单价</span>
</td>
<td align="center">
<span>商品描述</span>
</td>
</tr>
<tr>
<td style="width: 200px" align="center">
<asp:TextBox ID="txtProductName" runat="server" Width="200px"></asp:TextBox>
</td>
<td style="width: 200px" align="center">
<asp:TextBox ID="txtUnitPrice" runat="server" Width="200px"></asp:TextBox>
</td>
<td style="width: 200px" align="center">
<asp:TextBox ID="txtDescription" runat="server" Width="200px"></asp:TextBox>
</td>
</tr>
</table>
用户控件后台 EditProductCtrl.ascx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
namespace RepeaterDemo
{
public partial class EditProductCtrl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
/// <summary>
/// 商品名
/// </summary>
public string ProductName
{
get { return txtProductName.Text; }
set { txtProductName.Text = value; }
}
/// <summary>
/// 商品单价
/// </summary>
public decimal UnitPrice
{
get
{
Regex regx = new Regex(@"^/d+$");
string unitPrice = txtUnitPrice.Text.Trim();
if (unitPrice.Contains("."))
{
unitPrice = unitPrice.Substring(0, unitPrice.IndexOf("."));
return regx.IsMatch(unitPrice) ? Convert.ToDecimal(unitPrice) : 0;
}
else
{
return regx.IsMatch(unitPrice) ? Convert.ToDecimal(unitPrice) : 0;
}
}
set { txtUnitPrice.Text = value.ToString(); }
}
/// <summary>
/// 商品描述
/// </summary>
public string Description
{
get { return txtDescription.Text; }
set { txtDescription.Text = value; }
}
}
}