<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PageSaveData.aspx.cs" Inherits="PageSaveData" %>
<!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">
<div style="text-align: center">
<br />
<br />
<br />
<table >
<tr>
<td>
<asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="保 存(S)"
Width="120px" Height="32px" Font-Size="Medium" AccessKey="S"
ToolTip="快捷键(Alt+S)" /> </td>
<td>
<asp:Button ID="btnExcel" runat="server" Height="32px" οnclick="btnExcel_Click"
Text="Excel 表(E)" Width="120px" AccessKey="E" ToolTip="快捷键(Alt+E)" />
</td>
<td>
<asp:Button ID="btnBack" runat="server" Font-Size="Medium" Height="32px"
οnclick="btnBack_Click" Text="返 回(B)" Width="120px" AccessKey="B"
ToolTip="快捷键(Alt+B)" />
</td>
</tr>
</table>
<br />
<asp:GridView ID="gridViewDB" runat="server" BackColor="#DEBA84"
BorderColor="#DEBA84" BorderWidth="1px" CellPadding="3" CellSpacing="2" Height="293px"
Width="663px" AutoGenerateColumns="False" Caption="数据库" OnRowDeleting="gridViewDB_RowDeleting"
style="text-align: center" onrowdeleted="gridViewDB_RowDeleted"
onrowdatabound="gridViewDB_RowDataBound" AllowPaging="True"
onpageindexchanging="gridViewDB_PageIndexChanging"
onrowupdating="gridViewDB_RowUpdating"
DataKeyNames="UserName"
onrowcancelingedit="gridViewDB_RowCancelingEdit"
onrowediting="gridViewDB_RowEditing"
onrowupdated="gridViewDB_RowUpdated">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="BlueViolet" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="checkedAll" runat="server" Text="全选" AccessKey="A" ToolTip="快捷键(Alt+A)" OnCheckedChanged="checkedAll_CheckedChanged" AutoPostBack="True" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="checkedItem" runat="server" Text= '<%# Container.DisplayIndex + 1 %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UserName" HeaderText="用户名" ReadOnly="True" />
<asp:TemplateField HeaderText="电子邮件">
<EditItemTemplate>
<asp:TextBox ID="UserEmail" runat="server" Text='<%# Bind("UserEmail") %>'></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="UserEmail" ErrorMessage="Email 格式有误"
ValidationExpression="/w+([-+.']/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*"></asp:RegularExpressionValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server"
Text='<%# Bind("UserEmail") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="时间">
<EditItemTemplate>
<asp:Calendar ID="SendTime" runat="server" BackColor="#FFFFCC"
BorderColor="#FFCC66" BorderWidth="1px" DayNameFormat="Shortest"
Font-Names="Verdana" Font-Size="8pt" ForeColor="#663399" Height="200px"
SelectedDate='<%# Bind("SendTime") %>' VisibleDate='<%# Bind("SendTime") %>' ShowGridLines="True" Width="220px">
<SelectedDayStyle BackColor="#CCCCFF" Font-Bold="True" />
<SelectorStyle BackColor="#FFCC66" />
<TodayDayStyle BackColor="#FFCC66" ForeColor="White" />
<OtherMonthDayStyle ForeColor="#CC9966" />
<NextPrevStyle Font-Size="9pt" ForeColor="#FFFFCC" />
<DayHeaderStyle BackColor="#FFCC66" Font-Bold="True" Height="1px" />
<TitleStyle BackColor="#990000" Font-Bold="True" Font-Size="9pt"
ForeColor="#FFFFCC" />
</asp:Calendar>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("SendTime", "{0:yyyy-MM-dd}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="内容">
<EditItemTemplate>
<asp:TextBox ID="Content" runat="server" Text='<%# Bind("Content") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Content") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
<asp:CommandField ShowEditButton="True" HeaderText="编辑" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Web.UI.WebControls;
public partial class PageSaveData : System.Web.UI.Page
{
#region Page_Load
private static DataView dataView;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dataView = UserSchema.UserTable.AsDataView();
gridViewDB.DataSource = dataView;
gridViewDB.DataBind();
gridViewDB.Caption = Session["Title"] + "";
}
Page.Title = gridViewDB.Caption;
}
#endregion
#region location.href
protected void btnBack_Click(object sender, EventArgs e)
{
Response.Write("<script>window.top.location.href='PageLoadData.aspx'</script>");
}
#endregion
#region PrintToExcel
protected void btnExcel_Click(object sender, EventArgs e)
{
dataView.ToTable().PrintToExcel(gridViewDB.Caption);
}
#endregion
#region RowDataBound
protected void gridViewDB_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "bgColor=this.style.backgroundColor;this.style.backgroundColor='violet';this.style.cursor='hand';");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=bgColor");
string value = string.Format("return confirm('确实要删除编号“{0}”吗?');", e.Row.Cells[1].Text);
e.Row.Cells[5].Attributes.Add("OnClick", value);
}
}
#endregion
#region CheckedAll
protected void checkedAll_CheckedChanged(object sender, EventArgs e)
{
bool isChecked = (gridViewDB.HeaderRow.FindControl("checkedAll") as CheckBox).Checked;
var query = from row in gridViewDB.Rows.Cast<GridViewRow>()
let Check = row.FindControl("checkedItem") as CheckBox
select Check;
foreach (CheckBox item in query)
{
item.Checked = isChecked;
}
}
#endregion
#region GridView.Events
protected void gridViewDB_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridViewDB.PageIndex = e.NewPageIndex;
gridViewDB.DataSource = dataView;
gridViewDB.DataBind();
}
protected void gridViewDB_RowEditing(object sender, GridViewEditEventArgs e)
{
gridViewDB.EditIndex = e.NewEditIndex;
gridViewDB.DataSource = dataView;
gridViewDB.DataBind();
}
protected void gridViewDB_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gridViewDB.EditIndex = -1;
gridViewDB.DataSource = dataView;
gridViewDB.DataBind();
}
#endregion
#region UpdateRow
protected void gridViewDB_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DataRow updateRow = dataView[gridViewDB.Rows[e.RowIndex].DataItemIndex].Row;
try
{
updateRow.BeginEdit();
GridViewRow row = gridViewDB.Rows[e.RowIndex];
updateRow.SetField<string>("UserEmail", (row.FindControl("UserEmail") as TextBox).Text);
updateRow.SetField<string>("Content", (row.FindControl("Content") as TextBox).Text);
updateRow.SetField<DateTime>("SendTime", (row.FindControl("SendTime") as Calendar).SelectedDate);
updateRow.EndEdit();
btnSave.Enabled = true;
}
catch (Exception se)
{
Response.Write(se.Message);
updateRow.ClearErrors();
updateRow.CancelEdit();
}
finally
{
gridViewDB.EditIndex = -1;
gridViewDB.DataSource = dataView;
gridViewDB.DataBind();
}
}
protected void gridViewDB_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
if (e.Exception != null)
{
Response.Write(e.Exception.Message);
e.ExceptionHandled = true;
}
}
#endregion
#region DeleteRow
protected void gridViewDB_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataRow deleteRow = dataView[gridViewDB.Rows[e.RowIndex].DataItemIndex].Row;
try
{
deleteRow.Delete();
btnSave.Enabled = true;
}
catch (Exception se)
{
Response.Write(se.Message);
deleteRow.ClearErrors();
deleteRow.RejectChanges();
}
finally
{
gridViewDB.DataSource = dataView;
gridViewDB.DataBind();
}
}
protected void gridViewDB_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
if (e.Exception != null)
{
Response.Write(e.Exception.Message);
e.ExceptionHandled = true;
}
}
#endregion
#region SavaData
protected void btnSave_Click(object sender, EventArgs e)
{
switch (gridViewDB.Caption)
{
case "XML数据库":
FileInfo info = new FileInfo(Server.MapPath("~/App_Data/User.xml"));
if (info.Exists)
info.Attributes = FileAttributes.Normal;
using (StreamWriter writer = info.CreateText())
{
dataView.Table.WriteXml(writer, XmlWriteMode.IgnoreSchema);
dataView.Table.AcceptChanges();
}
break;
case "Access数据库":
try
{
DataTable table = dataView.Table.GetChanges();
if (table == null)
return;
using (OleDbDataAdapter adapter = new OleDbDataAdapter())
{
OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder();
builder.Provider = "Microsoft.ACE.OLEDB.12.0";
builder.DataSource = @"|DataDirectory|/User.accdb";
builder["Jet OLEDB:Database Password"] = "jinzhexian";
OleDbCommand cmd = new OleDbConnection(builder.ConnectionString).CreateCommand();
cmd.CommandText = "delete from [User] where UserName=?";
cmd.Parameters.Add("@UserName", OleDbType.VarWChar, 20, "UserName");
adapter.DeleteCommand = cmd;
cmd = cmd.Clone();
cmd.CommandText = "insert into [User] values(?,?,?,?)";
cmd.Parameters.Add("@UserEmail", OleDbType.VarWChar, 50, "UserEmail");
cmd.Parameters.Add("@Content", OleDbType.VarWChar, 255, "Content");
cmd.Parameters.Add("@SendTime", OleDbType.DBDate, 8, "SendTime");
adapter.InsertCommand = cmd;
cmd = cmd.Clone();
cmd.CommandText = "update [User] set UserEmail=?,Content=?,SendTime=? where UserName=?";
cmd.Parameters.RemoveAt("@UserName");
cmd.Parameters.Add("@UserName", OleDbType.VarWChar, 20, "UserName");
adapter.UpdateCommand = cmd;
adapter.Update(table);
dataView.Table.AcceptChanges();
}
}
catch (Exception se)
{
Response.Write(se.Message);
}
break;
}
gridViewDB.DataSource = dataView;
gridViewDB.DataBind();
btnSave.Enabled = false;
}
#endregion
}