<%@ Page Language="C#" AutoEventWireup="true" CodeFile="yttdj.aspx.cs" Inherits="yttdj" %>
<!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>
<style type="text/css">
.style1
{
font-family: 楷体_GB2312;
font-size: xx-large;
background-color: #66FFCC;
}
.style2
{
text-align: center;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="style2" style="height: 759px">
<div class="style2">
<div class="style2">
<br />
<br />
<span class="style1">绒山羊淘汰登记表</span><br />
<br />
</div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" BackColor="#DEBA84"
BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3"
CellSpacing="2" DataKeyNames="yhao" DataSourceID="SqlDataSourceytt"
Height="301px" PageSize="15" Width="546px"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="yhao" HeaderText="羊号" ReadOnly="True"
SortExpression="yhao" />
<asp:BoundField DataField="ysex" HeaderText="公母" SortExpression="ysex" />
<asp:BoundField DataField="lichang" HeaderText="离场(淘汰)类型"
SortExpression="lichang" />
<asp:BoundField DataField="lidate" HeaderText="离场时间" SortExpression="lidate" />
<asp:CommandField ShowEditButton="True">
<HeaderStyle Width="10px" />
</asp:CommandField>
<asp:ButtonField CommandName="Insert" Text="新建" />
</Columns>
<EmptyDataTemplate>
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False"
DataKeyNames="yhao" DataSourceID="SqlDataSourceytt" Height="50px" Width="125px">
<Fields>
<asp:BoundField DataField="yhao" HeaderText="yhao" ReadOnly="True"
SortExpression="yhao" />
<asp:BoundField DataField="ysex" HeaderText="ysex" SortExpression="ysex" />
<asp:BoundField DataField="lichang" HeaderText="lichang"
SortExpression="lichang" />
<asp:BoundField DataField="lidate" HeaderText="lidate"
SortExpression="lidate" />
<asp:CommandField ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
</EmptyDataTemplate>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
</div>
<asp:SqlDataSource ID="SqlDataSourceytt" runat="server"
ConflictDetection="CompareAllValues"
ConnectionString="<%$ ConnectionStrings:rongshanyangConnectionString2 %>"
DeleteCommand="DELETE FROM [yxinxi] WHERE [yhao] = @original_yhao AND (([ysex] = @original_ysex) OR ([ysex] IS NULL AND @original_ysex IS NULL)) AND (([lichang] = @original_lichang) OR ([lichang] IS NULL AND @original_lichang IS NULL)) AND (([lidate] = @original_lidate) OR ([lidate] IS NULL AND @original_lidate IS NULL))"
InsertCommand="INSERT INTO [yxinxi] ([yhao], [ysex], [lichang], [lidate]) VALUES (@yhao, @ysex, @lichang, @lidate)"
OldValuesParameterFormatString="original_{0}"
SelectCommand="SELECT [yhao], [ysex], [lichang], [lidate] FROM [yxinxi]"
UpdateCommand="UPDATE [yxinxi] SET [ysex] = @ysex, [lichang] = @lichang, [lidate] = @lidate WHERE [yhao] = @original_yhao AND (([ysex] = @original_ysex) OR ([ysex] IS NULL AND @original_ysex IS NULL)) AND (([lichang] = @original_lichang) OR ([lichang] IS NULL AND @original_lichang IS NULL)) AND (([lidate] = @original_lidate) OR ([lidate] IS NULL AND @original_lidate IS NULL))">
<DeleteParameters>
<asp:Parameter Name="original_yhao" Type="String" />
<asp:Parameter Name="original_ysex" Type="String" />
<asp:Parameter Name="original_lichang" Type="String" />
<asp:Parameter Name="original_lidate" Type="String" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="yhao" Type="String" />
<asp:Parameter Name="ysex" Type="String" />
<asp:Parameter Name="lichang" Type="String" />
<asp:Parameter Name="lidate" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="ysex" Type="String" />
<asp:Parameter Name="lichang" Type="String" />
<asp:Parameter Name="lidate" Type="String" />
<asp:Parameter Name="original_yhao" Type="String" />
<asp:Parameter Name="original_ysex" Type="String" />
<asp:Parameter Name="original_lichang" Type="String" />
<asp:Parameter Name="original_lidate" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
<div class="style2">
<asp:Button ID="btnyttexcel" runat="server" Font-Size="11pt" Height="38px"
onclick="btnyttexcel_Click" Text="将此页导出为excle表" Width="155px" />
<br />
<br />
</div>
</div>
</form>
</body>
</html>
据说是可以用where 语句可以解决空值更新问题,那么对于我这段代码该怎么改呢?
还有就是 我用的是VS2010的环境,gridview里边没有“插入”这个选项,只有“编辑,删除,更新选择等”,而且删除好像还不起作用,是怎么回事啊,大家知道的请指教一下啊~~急急急~~~~
8 个解决方案
#1
更新的时候你需要判断是否是空值。另外数据库字段也可以设置是否允许空值
#2
你可以参考这个例子,自己控制起来很方便
GridView 插入、删除、修改、分页的综合例子
本文提供一个综合实现GridView 插入、删除、修改的例子,本例子不依赖GridView的内置功能,完全采取自定义的做法,更能符合操作习惯。当然,本例子增加排序、分页的功能也非常简单,因为GridView显示的数据只是当前页的数据,所以,不影响分页。效果如图:
完整的源代码:
ASPX 代码
<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="true" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<script runat="server">
private int EditId = 0;
private String ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\ASPNET20Book.mdb;";
/// <summary>
/// 显示图片,在图片不存在时显示一个 none.gif
/// </summary>
/// <param name="pathPhoto"></param>
/// <returns></returns>
private string GetUserPhoto(object pathPhoto)
{
if (pathPhoto == DBNull.Value)
{
return "<img src='Images/none.gif'>";
}
else
{
return "<img src='" + pathPhoto.ToString() + "'>";
}
}
/// <summary>
/// 数据绑定的处理。在需要编辑时,显示出编辑框
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (EditId > 0)
{
//如果绑定数据源是DatarReader,则使用下面的方法:
//System.Data.Common.DbDataRecord rowItem = (System.Data.Common.DbDataRecord)e.Row.DataItem;
//如果绑定是 DataView,则使用此方法
System.Data.DataRowView rowItem = (System.Data.DataRowView)e.Row.DataItem;
if (rowItem["id"].ToString().Equals(EditId.ToString()))
{
//隐藏显示的文字
PlaceHolder LabelTitle = e.Row.FindControl("LabelTitle") as PlaceHolder;
LabelTitle.Visible = false;
PlaceHolder LabelBirthday = e.Row.FindControl("LabelBirthday") as PlaceHolder;
LabelBirthday.Visible = false;
PlaceHolder LabelGender = e.Row.FindControl("LabelGender") as PlaceHolder;
LabelGender.Visible = false;
PlaceHolder LabelClassName = e.Row.FindControl("LabelClassName") as PlaceHolder;
LabelClassName.Visible = false;
PlaceHolder LabelPhoto = e.Row.FindControl("LabelPhoto") as PlaceHolder;
LabelPhoto.Visible = false;
//打开编辑框
TextBox uTitle = e.Row.FindControl("uTitle") as TextBox;
uTitle.Visible = true;
TextBox uBirthDay = e.Row.FindControl("uBirthDay") as TextBox;
uBirthDay.Visible = true;
RadioButtonList uGender = e.Row.FindControl("uGender") as RadioButtonList;
uGender.Visible = true;
DropDownList uClassName = e.Row.FindControl("uClassName") as DropDownList;
uClassName.Visible = true;
FileUpload uPhoto = e.Row.FindControl("uPhoto") as FileUpload;
uPhoto.Visible = true;
//赋原来的值
if (rowItem["Gender"] != DBNull.Value)
{
uGender.SelectedIndex = (Convert.ToBoolean(rowItem["Gender"]) ? 0 : 1);
}
if (rowItem["ClassName"] != DBNull.Value)
{
uClassName.Items.FindByText(rowItem["ClassName"].ToString()).Selected = true;
}
//显示编辑更新按钮
Panel PanelNormal = e.Row.FindControl("PanelNormal") as Panel;
PanelNormal.Visible = false;
Panel PanelUpdate = e.Row.FindControl("PanelUpdate") as Panel;
PanelUpdate.Visible = true;
}
}
}
}
/// <summary>
/// 打开编辑框,将编辑标识传递到 EditId
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void EditClick(object sender, EventArgs e)
{
Button b = sender as Button;
EditId = Convert.ToInt32(b.CommandArgument);
GridViewRow dvr = b.NamingContainer as GridViewRow;
EditId = (int)GridView1.DataKeys[dvr.DataItemIndex].Value;
DataBind();
//Response.Write(GridView1.DataKeys[dvr.DataItemIndex].Value);
}
/// <summary>
/// 将编辑的数据保存
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void UpdateClick(object sender, EventArgs e)
{
Button b = sender as Button;
GridViewRow dvr = b.NamingContainer as GridViewRow;
TextBox uTitle = dvr.FindControl("uTitle") as TextBox;
string StudentTitle = uTitle.Text;
string StudentBirthDay = ((TextBox)dvr.FindControl("uBirthDay")).Text;
bool StudentGender = ((RadioButtonList)dvr.FindControl("uGender")).SelectedValue == "男" ? true : false;
string StudentClassName = ((DropDownList)dvr.FindControl("uClassName")).SelectedValue;
string StudentID = GridView1.DataKeys[dvr.RowIndex].Value.ToString();
string sql = "";
String PhotoPath = "";
bool HasFileUploaded = false;
FileUpload oUpload = (FileUpload)dvr.FindControl("uPhoto");
if (oUpload.HasFile)
{
PhotoPath = Guid.NewGuid().ToString("D") + System.IO.Path.GetExtension(oUpload.FileName);
oUpload.SaveAs(Server.MapPath("~") + "\\" + PhotoPath);
HasFileUploaded = true;
}
if (HasFileUploaded)
{
sql = "Update Student Set Title=@Title,BirthDay = @BirthDay,";
sql += "Gender=@Gender,PhotoPath=@PhotoPath,ClassName=@ClassName Where id=@id";
}
else
{
sql = "Update Student Set Title=@Title,BirthDay = @BirthDay,";
sql += "Gender=@Gender,ClassName=@ClassName Where id=@id";
}
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.Parameters.AddWithValue("@Title", StudentTitle);
cmd.Parameters.AddWithValue("@BirthDay", StudentBirthDay);
cmd.Parameters.AddWithValue("@Gender", StudentGender);
if (HasFileUploaded)
{
cmd.Parameters.AddWithValue("@PhotoPath", PhotoPath);
}
cmd.Parameters.AddWithValue("@ClassName", StudentClassName);
cmd.Parameters.AddWithValue("@id", StudentID);
cmd.ExecuteNonQuery();
cn.Close();
Response.Redirect(Request.Url.ToString());
}
/// <summary>
/// 添加新记录
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void AddClick(object sender, EventArgs e)
{
InsertNewRecord(sender, e);
}
/// <summary>
/// 取消编辑
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void CancelClick(object sender, EventArgs e)
{
Response.Redirect(Request.UrlReferrer.ToString());
}
/// <summary>
/// 删除记录
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void DeleteClick(object sender, EventArgs e)
{
Button b = sender as Button;
int id = Convert.ToInt32(b.CommandArgument);
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
OleDbCommand cmd = new OleDbCommand("Delete From [Student] Where [id]=@id", cn);
cmd.Parameters.AddWithValue("@id", id);
cmd.ExecuteNonQuery();
cn.Close();
Response.Redirect(Request.Url.ToString());
}
/// <summary>
/// 插入新记录的公共函数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void InsertNewRecord(object sender, EventArgs e)
{
string StudentTitle = ((TextBox)(sender as Button).NamingContainer.FindControl("NewTitle")).Text;
if (StudentTitle.Trim() == "")
{
ErrorMsg.Text = "请输入姓名";
return;
}
string StudentBirthDay = ((TextBox)(sender as Button).NamingContainer.FindControl("NewBirthDay")).Text;
bool StudentGender = ((RadioButtonList)
(sender as Button).NamingContainer.FindControl("NewGender")).SelectedValue == "男" ? true : false;
string StudentClassName = ((DropDownList)
(sender as Button).NamingContainer.FindControl("NewClassName")).SelectedValue;
FileUpload oUpload = (FileUpload)(sender as Button).NamingContainer.FindControl("AddPhoto");
String FileName = "";
FileName = Guid.NewGuid().ToString("D") + System.IO.Path.GetExtension(oUpload.FileName);
oUpload.SaveAs(Server.MapPath("~") + "\\" + FileName);
string sql = "Insert Into Student (Title,BirthDay,Gender,PhotoPath,ClassName)";
sql += " Values(@Title,@BirthDay,@Gender,@PhotoPath,@ClassName)";
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.Parameters.AddWithValue("@Title", StudentTitle);
cmd.Parameters.AddWithValue("@BirthDay", StudentBirthDay);
cmd.Parameters.AddWithValue("@Gender", StudentGender);
cmd.Parameters.AddWithValue("@PhotoPath", FileName);
cmd.Parameters.AddWithValue("@ClassName", StudentClassName);
cmd.ExecuteNonQuery();
cn.Close();
Response.Redirect(Request.FilePath.ToString());
}
/// <summary>
/// 生成 Google 样式的分页
/// </summary>
/// <param name="TotalCountRecord"></param>
/// <param name="CurrentPage"></param>
/// <param name="PageItem"></param>
GridView 插入、删除、修改、分页的综合例子
本文提供一个综合实现GridView 插入、删除、修改的例子,本例子不依赖GridView的内置功能,完全采取自定义的做法,更能符合操作习惯。当然,本例子增加排序、分页的功能也非常简单,因为GridView显示的数据只是当前页的数据,所以,不影响分页。效果如图:
完整的源代码:
ASPX 代码
<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="true" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<script runat="server">
private int EditId = 0;
private String ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\ASPNET20Book.mdb;";
/// <summary>
/// 显示图片,在图片不存在时显示一个 none.gif
/// </summary>
/// <param name="pathPhoto"></param>
/// <returns></returns>
private string GetUserPhoto(object pathPhoto)
{
if (pathPhoto == DBNull.Value)
{
return "<img src='Images/none.gif'>";
}
else
{
return "<img src='" + pathPhoto.ToString() + "'>";
}
}
/// <summary>
/// 数据绑定的处理。在需要编辑时,显示出编辑框
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (EditId > 0)
{
//如果绑定数据源是DatarReader,则使用下面的方法:
//System.Data.Common.DbDataRecord rowItem = (System.Data.Common.DbDataRecord)e.Row.DataItem;
//如果绑定是 DataView,则使用此方法
System.Data.DataRowView rowItem = (System.Data.DataRowView)e.Row.DataItem;
if (rowItem["id"].ToString().Equals(EditId.ToString()))
{
//隐藏显示的文字
PlaceHolder LabelTitle = e.Row.FindControl("LabelTitle") as PlaceHolder;
LabelTitle.Visible = false;
PlaceHolder LabelBirthday = e.Row.FindControl("LabelBirthday") as PlaceHolder;
LabelBirthday.Visible = false;
PlaceHolder LabelGender = e.Row.FindControl("LabelGender") as PlaceHolder;
LabelGender.Visible = false;
PlaceHolder LabelClassName = e.Row.FindControl("LabelClassName") as PlaceHolder;
LabelClassName.Visible = false;
PlaceHolder LabelPhoto = e.Row.FindControl("LabelPhoto") as PlaceHolder;
LabelPhoto.Visible = false;
//打开编辑框
TextBox uTitle = e.Row.FindControl("uTitle") as TextBox;
uTitle.Visible = true;
TextBox uBirthDay = e.Row.FindControl("uBirthDay") as TextBox;
uBirthDay.Visible = true;
RadioButtonList uGender = e.Row.FindControl("uGender") as RadioButtonList;
uGender.Visible = true;
DropDownList uClassName = e.Row.FindControl("uClassName") as DropDownList;
uClassName.Visible = true;
FileUpload uPhoto = e.Row.FindControl("uPhoto") as FileUpload;
uPhoto.Visible = true;
//赋原来的值
if (rowItem["Gender"] != DBNull.Value)
{
uGender.SelectedIndex = (Convert.ToBoolean(rowItem["Gender"]) ? 0 : 1);
}
if (rowItem["ClassName"] != DBNull.Value)
{
uClassName.Items.FindByText(rowItem["ClassName"].ToString()).Selected = true;
}
//显示编辑更新按钮
Panel PanelNormal = e.Row.FindControl("PanelNormal") as Panel;
PanelNormal.Visible = false;
Panel PanelUpdate = e.Row.FindControl("PanelUpdate") as Panel;
PanelUpdate.Visible = true;
}
}
}
}
/// <summary>
/// 打开编辑框,将编辑标识传递到 EditId
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void EditClick(object sender, EventArgs e)
{
Button b = sender as Button;
EditId = Convert.ToInt32(b.CommandArgument);
GridViewRow dvr = b.NamingContainer as GridViewRow;
EditId = (int)GridView1.DataKeys[dvr.DataItemIndex].Value;
DataBind();
//Response.Write(GridView1.DataKeys[dvr.DataItemIndex].Value);
}
/// <summary>
/// 将编辑的数据保存
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void UpdateClick(object sender, EventArgs e)
{
Button b = sender as Button;
GridViewRow dvr = b.NamingContainer as GridViewRow;
TextBox uTitle = dvr.FindControl("uTitle") as TextBox;
string StudentTitle = uTitle.Text;
string StudentBirthDay = ((TextBox)dvr.FindControl("uBirthDay")).Text;
bool StudentGender = ((RadioButtonList)dvr.FindControl("uGender")).SelectedValue == "男" ? true : false;
string StudentClassName = ((DropDownList)dvr.FindControl("uClassName")).SelectedValue;
string StudentID = GridView1.DataKeys[dvr.RowIndex].Value.ToString();
string sql = "";
String PhotoPath = "";
bool HasFileUploaded = false;
FileUpload oUpload = (FileUpload)dvr.FindControl("uPhoto");
if (oUpload.HasFile)
{
PhotoPath = Guid.NewGuid().ToString("D") + System.IO.Path.GetExtension(oUpload.FileName);
oUpload.SaveAs(Server.MapPath("~") + "\\" + PhotoPath);
HasFileUploaded = true;
}
if (HasFileUploaded)
{
sql = "Update Student Set Title=@Title,BirthDay = @BirthDay,";
sql += "Gender=@Gender,PhotoPath=@PhotoPath,ClassName=@ClassName Where id=@id";
}
else
{
sql = "Update Student Set Title=@Title,BirthDay = @BirthDay,";
sql += "Gender=@Gender,ClassName=@ClassName Where id=@id";
}
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.Parameters.AddWithValue("@Title", StudentTitle);
cmd.Parameters.AddWithValue("@BirthDay", StudentBirthDay);
cmd.Parameters.AddWithValue("@Gender", StudentGender);
if (HasFileUploaded)
{
cmd.Parameters.AddWithValue("@PhotoPath", PhotoPath);
}
cmd.Parameters.AddWithValue("@ClassName", StudentClassName);
cmd.Parameters.AddWithValue("@id", StudentID);
cmd.ExecuteNonQuery();
cn.Close();
Response.Redirect(Request.Url.ToString());
}
/// <summary>
/// 添加新记录
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void AddClick(object sender, EventArgs e)
{
InsertNewRecord(sender, e);
}
/// <summary>
/// 取消编辑
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void CancelClick(object sender, EventArgs e)
{
Response.Redirect(Request.UrlReferrer.ToString());
}
/// <summary>
/// 删除记录
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void DeleteClick(object sender, EventArgs e)
{
Button b = sender as Button;
int id = Convert.ToInt32(b.CommandArgument);
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
OleDbCommand cmd = new OleDbCommand("Delete From [Student] Where [id]=@id", cn);
cmd.Parameters.AddWithValue("@id", id);
cmd.ExecuteNonQuery();
cn.Close();
Response.Redirect(Request.Url.ToString());
}
/// <summary>
/// 插入新记录的公共函数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void InsertNewRecord(object sender, EventArgs e)
{
string StudentTitle = ((TextBox)(sender as Button).NamingContainer.FindControl("NewTitle")).Text;
if (StudentTitle.Trim() == "")
{
ErrorMsg.Text = "请输入姓名";
return;
}
string StudentBirthDay = ((TextBox)(sender as Button).NamingContainer.FindControl("NewBirthDay")).Text;
bool StudentGender = ((RadioButtonList)
(sender as Button).NamingContainer.FindControl("NewGender")).SelectedValue == "男" ? true : false;
string StudentClassName = ((DropDownList)
(sender as Button).NamingContainer.FindControl("NewClassName")).SelectedValue;
FileUpload oUpload = (FileUpload)(sender as Button).NamingContainer.FindControl("AddPhoto");
String FileName = "";
FileName = Guid.NewGuid().ToString("D") + System.IO.Path.GetExtension(oUpload.FileName);
oUpload.SaveAs(Server.MapPath("~") + "\\" + FileName);
string sql = "Insert Into Student (Title,BirthDay,Gender,PhotoPath,ClassName)";
sql += " Values(@Title,@BirthDay,@Gender,@PhotoPath,@ClassName)";
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.Parameters.AddWithValue("@Title", StudentTitle);
cmd.Parameters.AddWithValue("@BirthDay", StudentBirthDay);
cmd.Parameters.AddWithValue("@Gender", StudentGender);
cmd.Parameters.AddWithValue("@PhotoPath", FileName);
cmd.Parameters.AddWithValue("@ClassName", StudentClassName);
cmd.ExecuteNonQuery();
cn.Close();
Response.Redirect(Request.FilePath.ToString());
}
/// <summary>
/// 生成 Google 样式的分页
/// </summary>
/// <param name="TotalCountRecord"></param>
/// <param name="CurrentPage"></param>
/// <param name="PageItem"></param>
#3
接上
//每页显示的记录数
private int PageItem = 10;
private void BuildPagers(int TotalCountRecord, int CurrentPage)
{
int Step = 6;
int LeftNum = 0;
int RightNum = 0;
String PageUrl = "?";
int PageCount = (int)Math.Ceiling((double)(TotalCountRecord) / PageItem);
if (CurrentPage - Step < 1)
{
LeftNum = 1;
}
else
{
LeftNum = CurrentPage - Step;
}
if (CurrentPage + Step > PageCount)
{
RightNum = PageCount;
}
else
{
RightNum = CurrentPage + Step;
}
string OutPut = "";
for (int i = LeftNum; i <= RightNum; i++)
{
if (i == CurrentPage)
{
OutPut += "<span style='color:red'>" + i.ToString() + "</span> ";
}
else
{
OutPut += "<a href=\"" + PageUrl + "Page=" + i.ToString() + "\">" + i.ToString() + "</a> ";
}
}
if (CurrentPage > 1)
{
OutPut = "<a href='" + PageUrl + "Page=1'>首页</a> <a href=\"" + PageUrl + "Page=" + (CurrentPage - 1) + "\">上一页</a> " + OutPut;
}
if (CurrentPage < PageCount)
{
OutPut += " <a href=\"" + PageUrl + "Page=" + (CurrentPage + 1) + "\">下一页</a> <a href='" + PageUrl + "Page=" + PageCount + "'>末页</a>";
}
Pager.InnerHtml = OutPut;
}
/// <summary>
/// 加载页面
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataBind();
}
}
/// <summary>
/// 绑定 GridView
/// </summary>
protected void DataBind()
{
OleDbCommand cmd;
String sql;
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
// 由于是 Access 数据库,我们只进行简单的分页。对于性能要求较高的地方,请自行采取其他方法。
sql = "SELECT COUNT(*) FROM [Student]";
cmd = new OleDbCommand(sql, cn);
// 总的记录数
int TotalCount = Convert.ToInt32(cmd.ExecuteScalar());
//当前页的序号
int PageIndex = 1;
String page = Request.QueryString["Page"];
if (page == null) page = "1";
Int32.TryParse(page, out PageIndex);
if (PageIndex < 1) PageIndex = 1;
int PageCount = (int)Math.Ceiling((double)(TotalCount) / PageItem);
if (PageIndex > PageCount) PageIndex = PageCount;
int startRecord = (PageIndex - 1) * PageItem;
sql = "SELECT * FROM [Student] ORDER BY [id] DESC";
OleDbDataAdapter da = new OleDbDataAdapter(sql, cn);
DataSet ds = new DataSet();
da.Fill(ds, startRecord, PageItem, "Student");
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
cn.Close();
BuildPagers(TotalCount, PageIndex);
}
</script>
<!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>GridView 插入、删除、修改的例子</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
OnRowDataBound="GridView1_RowDataBound" ShowFooter="true">
<HeaderStyle BackColor="#ccff99" Font-Bold="true" />
<Columns>
<asp:TemplateField HeaderText="姓名">
<ItemTemplate>
<asp:PlaceHolder ID="LabelTitle" runat="server">
<%#Eval("Title") %></asp:PlaceHolder>
<asp:TextBox ID="uTitle" runat="server" Text='<%#Eval("Title") %>' Visible="false"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="NewTitle" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="生日(yyyy-MM-dd格式)">
<ItemTemplate>
<asp:PlaceHolder ID="LabelBirthday" runat="server">
<%#Eval("BirthDay", "{0:yyyy-MM-dd}")%></asp:PlaceHolder>
<asp:TextBox ID="uBirthDay" runat="server" Text='<%#Eval("BirthDay", "{0:yyyy-MM-dd}")%> '
Visible="false" />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="NewBirthDay" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="性别">
<ItemTemplate>
<asp:PlaceHolder ID="LabelGender" runat="server">
<%#(Eval("Gender")).ToString() =="True"?"男":"女"%></asp:PlaceHolder>
<asp:RadioButtonList ID="uGender" runat="server" RepeatDirection="Horizontal" Visible="false">
<asp:ListItem Text="男"></asp:ListItem>
<asp:ListItem Text="女"></asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
<FooterTemplate>
<asp:RadioButtonList ID="NewGender" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Selected="true" Text="男"></asp:ListItem>
<asp:ListItem Text="女"></asp:ListItem>
</asp:RadioButtonList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="年级">
<ItemTemplate>
<asp:PlaceHolder ID="LabelClassName" runat="server">
<%#Eval("ClassName")%></asp:PlaceHolder>
<asp:DropDownList ID="uClassName" runat="server" Visible="false">
<asp:ListItem Text="小学" Value="小学"></asp:ListItem>
<asp:ListItem Text="中学" Value="中学"></asp:ListItem>
<asp:ListItem Text="高中" Value="高中"></asp:ListItem>
<asp:ListItem Text="大学" Value="大学"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="NewClassName" runat="server">
<asp:ListItem Text="小学" Value="小学"></asp:ListItem>
<asp:ListItem Text="中学" Value="中学"></asp:ListItem>
<asp:ListItem Text="高中" Value="高中"></asp:ListItem>
<asp:ListItem Text="大学" Value="大学"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="照片">
<ItemTemplate>
<asp:PlaceHolder ID="LabelPhoto" runat="server">
<%# GetUserPhoto(Eval("PhotoPath")) %></asp:PlaceHolder>
<asp:FileUpload ID="uPhoto" runat="server" Visible="false" />
</ItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="AddPhoto" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="操作">
<ItemTemplate>
<asp:Panel ID="PanelNormal" runat="server">
<asp:Button ID="EditButton" runat="server" Text="修改" OnClick="EditClick" CommandArgument='<%#Eval("id") %>' />
<asp:Button ID="DeleteButton" runat="server" Text="删除" OnClick="DeleteClick" CommandArgument='<%#Eval("id") %>' />
</asp:Panel>
<asp:Panel ID="PanelUpdate" runat="server" Visible="false">
<asp:Button ID="UpdateButton" runat="server" Text="更新" OnClick="UpdateClick" CommandArgument='<%#Eval("id") %>' />
<asp:Button ID="CancelButton" runat="server" Text="取消" OnClick="CancelClick" />
</asp:Panel>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="AddButton" runat="server" Text="添加新纪录" OnClick="AddClick" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<table cellspacing="0" rules="all" border="1" style="border-collapse: collapse;">
<tr>
<th>姓名</th>
<th>生日(yyyy-MM-dd格式)</th>
<th>性别</th>
<th>年级</th>
<th>照片</th>
<th>操作</th>
</tr>
<tr>
<td>
<asp:TextBox ID="NewTitle" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="NewBirthDay" runat="server"></asp:TextBox>
</td>
<td>
<asp:RadioButtonList ID="NewGender" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Selected="true" Text="男"></asp:ListItem>
<asp:ListItem Text="女"></asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:DropDownList ID="NewClassName" runat="server">
<asp:ListItem Text="小学" Value="小学"></asp:ListItem>
<asp:ListItem Text="中学" Value="中学"></asp:ListItem>
<asp:ListItem Text="高中" Value="高中"></asp:ListItem>
<asp:ListItem Text="大学" Value="大学"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:FileUpload ID="AddPhoto" runat="server" />
</td>
<td>
<asp:Button ID="b" runat="server" Text="添加学生" OnClick="AddClick" />
</td>
</tr>
</table>
</EmptyDataTemplate>
</asp:GridView>
<div id="Pager" runat="server" style="text-align:left;padding:10px 0;"></div>
<asp:Label ID="ErrorMsg" runat="server" ForeColor="red"></asp:Label>
</form>
</body>
</html>
//每页显示的记录数
private int PageItem = 10;
private void BuildPagers(int TotalCountRecord, int CurrentPage)
{
int Step = 6;
int LeftNum = 0;
int RightNum = 0;
String PageUrl = "?";
int PageCount = (int)Math.Ceiling((double)(TotalCountRecord) / PageItem);
if (CurrentPage - Step < 1)
{
LeftNum = 1;
}
else
{
LeftNum = CurrentPage - Step;
}
if (CurrentPage + Step > PageCount)
{
RightNum = PageCount;
}
else
{
RightNum = CurrentPage + Step;
}
string OutPut = "";
for (int i = LeftNum; i <= RightNum; i++)
{
if (i == CurrentPage)
{
OutPut += "<span style='color:red'>" + i.ToString() + "</span> ";
}
else
{
OutPut += "<a href=\"" + PageUrl + "Page=" + i.ToString() + "\">" + i.ToString() + "</a> ";
}
}
if (CurrentPage > 1)
{
OutPut = "<a href='" + PageUrl + "Page=1'>首页</a> <a href=\"" + PageUrl + "Page=" + (CurrentPage - 1) + "\">上一页</a> " + OutPut;
}
if (CurrentPage < PageCount)
{
OutPut += " <a href=\"" + PageUrl + "Page=" + (CurrentPage + 1) + "\">下一页</a> <a href='" + PageUrl + "Page=" + PageCount + "'>末页</a>";
}
Pager.InnerHtml = OutPut;
}
/// <summary>
/// 加载页面
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataBind();
}
}
/// <summary>
/// 绑定 GridView
/// </summary>
protected void DataBind()
{
OleDbCommand cmd;
String sql;
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
// 由于是 Access 数据库,我们只进行简单的分页。对于性能要求较高的地方,请自行采取其他方法。
sql = "SELECT COUNT(*) FROM [Student]";
cmd = new OleDbCommand(sql, cn);
// 总的记录数
int TotalCount = Convert.ToInt32(cmd.ExecuteScalar());
//当前页的序号
int PageIndex = 1;
String page = Request.QueryString["Page"];
if (page == null) page = "1";
Int32.TryParse(page, out PageIndex);
if (PageIndex < 1) PageIndex = 1;
int PageCount = (int)Math.Ceiling((double)(TotalCount) / PageItem);
if (PageIndex > PageCount) PageIndex = PageCount;
int startRecord = (PageIndex - 1) * PageItem;
sql = "SELECT * FROM [Student] ORDER BY [id] DESC";
OleDbDataAdapter da = new OleDbDataAdapter(sql, cn);
DataSet ds = new DataSet();
da.Fill(ds, startRecord, PageItem, "Student");
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
cn.Close();
BuildPagers(TotalCount, PageIndex);
}
</script>
<!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>GridView 插入、删除、修改的例子</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
OnRowDataBound="GridView1_RowDataBound" ShowFooter="true">
<HeaderStyle BackColor="#ccff99" Font-Bold="true" />
<Columns>
<asp:TemplateField HeaderText="姓名">
<ItemTemplate>
<asp:PlaceHolder ID="LabelTitle" runat="server">
<%#Eval("Title") %></asp:PlaceHolder>
<asp:TextBox ID="uTitle" runat="server" Text='<%#Eval("Title") %>' Visible="false"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="NewTitle" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="生日(yyyy-MM-dd格式)">
<ItemTemplate>
<asp:PlaceHolder ID="LabelBirthday" runat="server">
<%#Eval("BirthDay", "{0:yyyy-MM-dd}")%></asp:PlaceHolder>
<asp:TextBox ID="uBirthDay" runat="server" Text='<%#Eval("BirthDay", "{0:yyyy-MM-dd}")%> '
Visible="false" />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="NewBirthDay" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="性别">
<ItemTemplate>
<asp:PlaceHolder ID="LabelGender" runat="server">
<%#(Eval("Gender")).ToString() =="True"?"男":"女"%></asp:PlaceHolder>
<asp:RadioButtonList ID="uGender" runat="server" RepeatDirection="Horizontal" Visible="false">
<asp:ListItem Text="男"></asp:ListItem>
<asp:ListItem Text="女"></asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
<FooterTemplate>
<asp:RadioButtonList ID="NewGender" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Selected="true" Text="男"></asp:ListItem>
<asp:ListItem Text="女"></asp:ListItem>
</asp:RadioButtonList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="年级">
<ItemTemplate>
<asp:PlaceHolder ID="LabelClassName" runat="server">
<%#Eval("ClassName")%></asp:PlaceHolder>
<asp:DropDownList ID="uClassName" runat="server" Visible="false">
<asp:ListItem Text="小学" Value="小学"></asp:ListItem>
<asp:ListItem Text="中学" Value="中学"></asp:ListItem>
<asp:ListItem Text="高中" Value="高中"></asp:ListItem>
<asp:ListItem Text="大学" Value="大学"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="NewClassName" runat="server">
<asp:ListItem Text="小学" Value="小学"></asp:ListItem>
<asp:ListItem Text="中学" Value="中学"></asp:ListItem>
<asp:ListItem Text="高中" Value="高中"></asp:ListItem>
<asp:ListItem Text="大学" Value="大学"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="照片">
<ItemTemplate>
<asp:PlaceHolder ID="LabelPhoto" runat="server">
<%# GetUserPhoto(Eval("PhotoPath")) %></asp:PlaceHolder>
<asp:FileUpload ID="uPhoto" runat="server" Visible="false" />
</ItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="AddPhoto" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="操作">
<ItemTemplate>
<asp:Panel ID="PanelNormal" runat="server">
<asp:Button ID="EditButton" runat="server" Text="修改" OnClick="EditClick" CommandArgument='<%#Eval("id") %>' />
<asp:Button ID="DeleteButton" runat="server" Text="删除" OnClick="DeleteClick" CommandArgument='<%#Eval("id") %>' />
</asp:Panel>
<asp:Panel ID="PanelUpdate" runat="server" Visible="false">
<asp:Button ID="UpdateButton" runat="server" Text="更新" OnClick="UpdateClick" CommandArgument='<%#Eval("id") %>' />
<asp:Button ID="CancelButton" runat="server" Text="取消" OnClick="CancelClick" />
</asp:Panel>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="AddButton" runat="server" Text="添加新纪录" OnClick="AddClick" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<table cellspacing="0" rules="all" border="1" style="border-collapse: collapse;">
<tr>
<th>姓名</th>
<th>生日(yyyy-MM-dd格式)</th>
<th>性别</th>
<th>年级</th>
<th>照片</th>
<th>操作</th>
</tr>
<tr>
<td>
<asp:TextBox ID="NewTitle" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="NewBirthDay" runat="server"></asp:TextBox>
</td>
<td>
<asp:RadioButtonList ID="NewGender" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Selected="true" Text="男"></asp:ListItem>
<asp:ListItem Text="女"></asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:DropDownList ID="NewClassName" runat="server">
<asp:ListItem Text="小学" Value="小学"></asp:ListItem>
<asp:ListItem Text="中学" Value="中学"></asp:ListItem>
<asp:ListItem Text="高中" Value="高中"></asp:ListItem>
<asp:ListItem Text="大学" Value="大学"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:FileUpload ID="AddPhoto" runat="server" />
</td>
<td>
<asp:Button ID="b" runat="server" Text="添加学生" OnClick="AddClick" />
</td>
</tr>
</table>
</EmptyDataTemplate>
</asp:GridView>
<div id="Pager" runat="server" style="text-align:left;padding:10px 0;"></div>
<asp:Label ID="ErrorMsg" runat="server" ForeColor="red"></asp:Label>
</form>
</body>
</html>
#4
#5
#6
#7
#8
插入不好实现,要么试试级联更新?
空值更新好解决,
在更新出 where选项 之选定 主键 或者唯一判断一条数据的那个字段就可以 ,把含有NULL的都删掉
空值更新好解决,
在更新出 where选项 之选定 主键 或者唯一判断一条数据的那个字段就可以 ,把含有NULL的都删掉
#1
更新的时候你需要判断是否是空值。另外数据库字段也可以设置是否允许空值
#2
你可以参考这个例子,自己控制起来很方便
GridView 插入、删除、修改、分页的综合例子
本文提供一个综合实现GridView 插入、删除、修改的例子,本例子不依赖GridView的内置功能,完全采取自定义的做法,更能符合操作习惯。当然,本例子增加排序、分页的功能也非常简单,因为GridView显示的数据只是当前页的数据,所以,不影响分页。效果如图:
完整的源代码:
ASPX 代码
<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="true" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<script runat="server">
private int EditId = 0;
private String ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\ASPNET20Book.mdb;";
/// <summary>
/// 显示图片,在图片不存在时显示一个 none.gif
/// </summary>
/// <param name="pathPhoto"></param>
/// <returns></returns>
private string GetUserPhoto(object pathPhoto)
{
if (pathPhoto == DBNull.Value)
{
return "<img src='Images/none.gif'>";
}
else
{
return "<img src='" + pathPhoto.ToString() + "'>";
}
}
/// <summary>
/// 数据绑定的处理。在需要编辑时,显示出编辑框
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (EditId > 0)
{
//如果绑定数据源是DatarReader,则使用下面的方法:
//System.Data.Common.DbDataRecord rowItem = (System.Data.Common.DbDataRecord)e.Row.DataItem;
//如果绑定是 DataView,则使用此方法
System.Data.DataRowView rowItem = (System.Data.DataRowView)e.Row.DataItem;
if (rowItem["id"].ToString().Equals(EditId.ToString()))
{
//隐藏显示的文字
PlaceHolder LabelTitle = e.Row.FindControl("LabelTitle") as PlaceHolder;
LabelTitle.Visible = false;
PlaceHolder LabelBirthday = e.Row.FindControl("LabelBirthday") as PlaceHolder;
LabelBirthday.Visible = false;
PlaceHolder LabelGender = e.Row.FindControl("LabelGender") as PlaceHolder;
LabelGender.Visible = false;
PlaceHolder LabelClassName = e.Row.FindControl("LabelClassName") as PlaceHolder;
LabelClassName.Visible = false;
PlaceHolder LabelPhoto = e.Row.FindControl("LabelPhoto") as PlaceHolder;
LabelPhoto.Visible = false;
//打开编辑框
TextBox uTitle = e.Row.FindControl("uTitle") as TextBox;
uTitle.Visible = true;
TextBox uBirthDay = e.Row.FindControl("uBirthDay") as TextBox;
uBirthDay.Visible = true;
RadioButtonList uGender = e.Row.FindControl("uGender") as RadioButtonList;
uGender.Visible = true;
DropDownList uClassName = e.Row.FindControl("uClassName") as DropDownList;
uClassName.Visible = true;
FileUpload uPhoto = e.Row.FindControl("uPhoto") as FileUpload;
uPhoto.Visible = true;
//赋原来的值
if (rowItem["Gender"] != DBNull.Value)
{
uGender.SelectedIndex = (Convert.ToBoolean(rowItem["Gender"]) ? 0 : 1);
}
if (rowItem["ClassName"] != DBNull.Value)
{
uClassName.Items.FindByText(rowItem["ClassName"].ToString()).Selected = true;
}
//显示编辑更新按钮
Panel PanelNormal = e.Row.FindControl("PanelNormal") as Panel;
PanelNormal.Visible = false;
Panel PanelUpdate = e.Row.FindControl("PanelUpdate") as Panel;
PanelUpdate.Visible = true;
}
}
}
}
/// <summary>
/// 打开编辑框,将编辑标识传递到 EditId
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void EditClick(object sender, EventArgs e)
{
Button b = sender as Button;
EditId = Convert.ToInt32(b.CommandArgument);
GridViewRow dvr = b.NamingContainer as GridViewRow;
EditId = (int)GridView1.DataKeys[dvr.DataItemIndex].Value;
DataBind();
//Response.Write(GridView1.DataKeys[dvr.DataItemIndex].Value);
}
/// <summary>
/// 将编辑的数据保存
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void UpdateClick(object sender, EventArgs e)
{
Button b = sender as Button;
GridViewRow dvr = b.NamingContainer as GridViewRow;
TextBox uTitle = dvr.FindControl("uTitle") as TextBox;
string StudentTitle = uTitle.Text;
string StudentBirthDay = ((TextBox)dvr.FindControl("uBirthDay")).Text;
bool StudentGender = ((RadioButtonList)dvr.FindControl("uGender")).SelectedValue == "男" ? true : false;
string StudentClassName = ((DropDownList)dvr.FindControl("uClassName")).SelectedValue;
string StudentID = GridView1.DataKeys[dvr.RowIndex].Value.ToString();
string sql = "";
String PhotoPath = "";
bool HasFileUploaded = false;
FileUpload oUpload = (FileUpload)dvr.FindControl("uPhoto");
if (oUpload.HasFile)
{
PhotoPath = Guid.NewGuid().ToString("D") + System.IO.Path.GetExtension(oUpload.FileName);
oUpload.SaveAs(Server.MapPath("~") + "\\" + PhotoPath);
HasFileUploaded = true;
}
if (HasFileUploaded)
{
sql = "Update Student Set Title=@Title,BirthDay = @BirthDay,";
sql += "Gender=@Gender,PhotoPath=@PhotoPath,ClassName=@ClassName Where id=@id";
}
else
{
sql = "Update Student Set Title=@Title,BirthDay = @BirthDay,";
sql += "Gender=@Gender,ClassName=@ClassName Where id=@id";
}
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.Parameters.AddWithValue("@Title", StudentTitle);
cmd.Parameters.AddWithValue("@BirthDay", StudentBirthDay);
cmd.Parameters.AddWithValue("@Gender", StudentGender);
if (HasFileUploaded)
{
cmd.Parameters.AddWithValue("@PhotoPath", PhotoPath);
}
cmd.Parameters.AddWithValue("@ClassName", StudentClassName);
cmd.Parameters.AddWithValue("@id", StudentID);
cmd.ExecuteNonQuery();
cn.Close();
Response.Redirect(Request.Url.ToString());
}
/// <summary>
/// 添加新记录
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void AddClick(object sender, EventArgs e)
{
InsertNewRecord(sender, e);
}
/// <summary>
/// 取消编辑
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void CancelClick(object sender, EventArgs e)
{
Response.Redirect(Request.UrlReferrer.ToString());
}
/// <summary>
/// 删除记录
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void DeleteClick(object sender, EventArgs e)
{
Button b = sender as Button;
int id = Convert.ToInt32(b.CommandArgument);
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
OleDbCommand cmd = new OleDbCommand("Delete From [Student] Where [id]=@id", cn);
cmd.Parameters.AddWithValue("@id", id);
cmd.ExecuteNonQuery();
cn.Close();
Response.Redirect(Request.Url.ToString());
}
/// <summary>
/// 插入新记录的公共函数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void InsertNewRecord(object sender, EventArgs e)
{
string StudentTitle = ((TextBox)(sender as Button).NamingContainer.FindControl("NewTitle")).Text;
if (StudentTitle.Trim() == "")
{
ErrorMsg.Text = "请输入姓名";
return;
}
string StudentBirthDay = ((TextBox)(sender as Button).NamingContainer.FindControl("NewBirthDay")).Text;
bool StudentGender = ((RadioButtonList)
(sender as Button).NamingContainer.FindControl("NewGender")).SelectedValue == "男" ? true : false;
string StudentClassName = ((DropDownList)
(sender as Button).NamingContainer.FindControl("NewClassName")).SelectedValue;
FileUpload oUpload = (FileUpload)(sender as Button).NamingContainer.FindControl("AddPhoto");
String FileName = "";
FileName = Guid.NewGuid().ToString("D") + System.IO.Path.GetExtension(oUpload.FileName);
oUpload.SaveAs(Server.MapPath("~") + "\\" + FileName);
string sql = "Insert Into Student (Title,BirthDay,Gender,PhotoPath,ClassName)";
sql += " Values(@Title,@BirthDay,@Gender,@PhotoPath,@ClassName)";
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.Parameters.AddWithValue("@Title", StudentTitle);
cmd.Parameters.AddWithValue("@BirthDay", StudentBirthDay);
cmd.Parameters.AddWithValue("@Gender", StudentGender);
cmd.Parameters.AddWithValue("@PhotoPath", FileName);
cmd.Parameters.AddWithValue("@ClassName", StudentClassName);
cmd.ExecuteNonQuery();
cn.Close();
Response.Redirect(Request.FilePath.ToString());
}
/// <summary>
/// 生成 Google 样式的分页
/// </summary>
/// <param name="TotalCountRecord"></param>
/// <param name="CurrentPage"></param>
/// <param name="PageItem"></param>
GridView 插入、删除、修改、分页的综合例子
本文提供一个综合实现GridView 插入、删除、修改的例子,本例子不依赖GridView的内置功能,完全采取自定义的做法,更能符合操作习惯。当然,本例子增加排序、分页的功能也非常简单,因为GridView显示的数据只是当前页的数据,所以,不影响分页。效果如图:
完整的源代码:
ASPX 代码
<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="true" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<script runat="server">
private int EditId = 0;
private String ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\ASPNET20Book.mdb;";
/// <summary>
/// 显示图片,在图片不存在时显示一个 none.gif
/// </summary>
/// <param name="pathPhoto"></param>
/// <returns></returns>
private string GetUserPhoto(object pathPhoto)
{
if (pathPhoto == DBNull.Value)
{
return "<img src='Images/none.gif'>";
}
else
{
return "<img src='" + pathPhoto.ToString() + "'>";
}
}
/// <summary>
/// 数据绑定的处理。在需要编辑时,显示出编辑框
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (EditId > 0)
{
//如果绑定数据源是DatarReader,则使用下面的方法:
//System.Data.Common.DbDataRecord rowItem = (System.Data.Common.DbDataRecord)e.Row.DataItem;
//如果绑定是 DataView,则使用此方法
System.Data.DataRowView rowItem = (System.Data.DataRowView)e.Row.DataItem;
if (rowItem["id"].ToString().Equals(EditId.ToString()))
{
//隐藏显示的文字
PlaceHolder LabelTitle = e.Row.FindControl("LabelTitle") as PlaceHolder;
LabelTitle.Visible = false;
PlaceHolder LabelBirthday = e.Row.FindControl("LabelBirthday") as PlaceHolder;
LabelBirthday.Visible = false;
PlaceHolder LabelGender = e.Row.FindControl("LabelGender") as PlaceHolder;
LabelGender.Visible = false;
PlaceHolder LabelClassName = e.Row.FindControl("LabelClassName") as PlaceHolder;
LabelClassName.Visible = false;
PlaceHolder LabelPhoto = e.Row.FindControl("LabelPhoto") as PlaceHolder;
LabelPhoto.Visible = false;
//打开编辑框
TextBox uTitle = e.Row.FindControl("uTitle") as TextBox;
uTitle.Visible = true;
TextBox uBirthDay = e.Row.FindControl("uBirthDay") as TextBox;
uBirthDay.Visible = true;
RadioButtonList uGender = e.Row.FindControl("uGender") as RadioButtonList;
uGender.Visible = true;
DropDownList uClassName = e.Row.FindControl("uClassName") as DropDownList;
uClassName.Visible = true;
FileUpload uPhoto = e.Row.FindControl("uPhoto") as FileUpload;
uPhoto.Visible = true;
//赋原来的值
if (rowItem["Gender"] != DBNull.Value)
{
uGender.SelectedIndex = (Convert.ToBoolean(rowItem["Gender"]) ? 0 : 1);
}
if (rowItem["ClassName"] != DBNull.Value)
{
uClassName.Items.FindByText(rowItem["ClassName"].ToString()).Selected = true;
}
//显示编辑更新按钮
Panel PanelNormal = e.Row.FindControl("PanelNormal") as Panel;
PanelNormal.Visible = false;
Panel PanelUpdate = e.Row.FindControl("PanelUpdate") as Panel;
PanelUpdate.Visible = true;
}
}
}
}
/// <summary>
/// 打开编辑框,将编辑标识传递到 EditId
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void EditClick(object sender, EventArgs e)
{
Button b = sender as Button;
EditId = Convert.ToInt32(b.CommandArgument);
GridViewRow dvr = b.NamingContainer as GridViewRow;
EditId = (int)GridView1.DataKeys[dvr.DataItemIndex].Value;
DataBind();
//Response.Write(GridView1.DataKeys[dvr.DataItemIndex].Value);
}
/// <summary>
/// 将编辑的数据保存
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void UpdateClick(object sender, EventArgs e)
{
Button b = sender as Button;
GridViewRow dvr = b.NamingContainer as GridViewRow;
TextBox uTitle = dvr.FindControl("uTitle") as TextBox;
string StudentTitle = uTitle.Text;
string StudentBirthDay = ((TextBox)dvr.FindControl("uBirthDay")).Text;
bool StudentGender = ((RadioButtonList)dvr.FindControl("uGender")).SelectedValue == "男" ? true : false;
string StudentClassName = ((DropDownList)dvr.FindControl("uClassName")).SelectedValue;
string StudentID = GridView1.DataKeys[dvr.RowIndex].Value.ToString();
string sql = "";
String PhotoPath = "";
bool HasFileUploaded = false;
FileUpload oUpload = (FileUpload)dvr.FindControl("uPhoto");
if (oUpload.HasFile)
{
PhotoPath = Guid.NewGuid().ToString("D") + System.IO.Path.GetExtension(oUpload.FileName);
oUpload.SaveAs(Server.MapPath("~") + "\\" + PhotoPath);
HasFileUploaded = true;
}
if (HasFileUploaded)
{
sql = "Update Student Set Title=@Title,BirthDay = @BirthDay,";
sql += "Gender=@Gender,PhotoPath=@PhotoPath,ClassName=@ClassName Where id=@id";
}
else
{
sql = "Update Student Set Title=@Title,BirthDay = @BirthDay,";
sql += "Gender=@Gender,ClassName=@ClassName Where id=@id";
}
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.Parameters.AddWithValue("@Title", StudentTitle);
cmd.Parameters.AddWithValue("@BirthDay", StudentBirthDay);
cmd.Parameters.AddWithValue("@Gender", StudentGender);
if (HasFileUploaded)
{
cmd.Parameters.AddWithValue("@PhotoPath", PhotoPath);
}
cmd.Parameters.AddWithValue("@ClassName", StudentClassName);
cmd.Parameters.AddWithValue("@id", StudentID);
cmd.ExecuteNonQuery();
cn.Close();
Response.Redirect(Request.Url.ToString());
}
/// <summary>
/// 添加新记录
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void AddClick(object sender, EventArgs e)
{
InsertNewRecord(sender, e);
}
/// <summary>
/// 取消编辑
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void CancelClick(object sender, EventArgs e)
{
Response.Redirect(Request.UrlReferrer.ToString());
}
/// <summary>
/// 删除记录
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void DeleteClick(object sender, EventArgs e)
{
Button b = sender as Button;
int id = Convert.ToInt32(b.CommandArgument);
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
OleDbCommand cmd = new OleDbCommand("Delete From [Student] Where [id]=@id", cn);
cmd.Parameters.AddWithValue("@id", id);
cmd.ExecuteNonQuery();
cn.Close();
Response.Redirect(Request.Url.ToString());
}
/// <summary>
/// 插入新记录的公共函数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void InsertNewRecord(object sender, EventArgs e)
{
string StudentTitle = ((TextBox)(sender as Button).NamingContainer.FindControl("NewTitle")).Text;
if (StudentTitle.Trim() == "")
{
ErrorMsg.Text = "请输入姓名";
return;
}
string StudentBirthDay = ((TextBox)(sender as Button).NamingContainer.FindControl("NewBirthDay")).Text;
bool StudentGender = ((RadioButtonList)
(sender as Button).NamingContainer.FindControl("NewGender")).SelectedValue == "男" ? true : false;
string StudentClassName = ((DropDownList)
(sender as Button).NamingContainer.FindControl("NewClassName")).SelectedValue;
FileUpload oUpload = (FileUpload)(sender as Button).NamingContainer.FindControl("AddPhoto");
String FileName = "";
FileName = Guid.NewGuid().ToString("D") + System.IO.Path.GetExtension(oUpload.FileName);
oUpload.SaveAs(Server.MapPath("~") + "\\" + FileName);
string sql = "Insert Into Student (Title,BirthDay,Gender,PhotoPath,ClassName)";
sql += " Values(@Title,@BirthDay,@Gender,@PhotoPath,@ClassName)";
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.Parameters.AddWithValue("@Title", StudentTitle);
cmd.Parameters.AddWithValue("@BirthDay", StudentBirthDay);
cmd.Parameters.AddWithValue("@Gender", StudentGender);
cmd.Parameters.AddWithValue("@PhotoPath", FileName);
cmd.Parameters.AddWithValue("@ClassName", StudentClassName);
cmd.ExecuteNonQuery();
cn.Close();
Response.Redirect(Request.FilePath.ToString());
}
/// <summary>
/// 生成 Google 样式的分页
/// </summary>
/// <param name="TotalCountRecord"></param>
/// <param name="CurrentPage"></param>
/// <param name="PageItem"></param>
#3
接上
//每页显示的记录数
private int PageItem = 10;
private void BuildPagers(int TotalCountRecord, int CurrentPage)
{
int Step = 6;
int LeftNum = 0;
int RightNum = 0;
String PageUrl = "?";
int PageCount = (int)Math.Ceiling((double)(TotalCountRecord) / PageItem);
if (CurrentPage - Step < 1)
{
LeftNum = 1;
}
else
{
LeftNum = CurrentPage - Step;
}
if (CurrentPage + Step > PageCount)
{
RightNum = PageCount;
}
else
{
RightNum = CurrentPage + Step;
}
string OutPut = "";
for (int i = LeftNum; i <= RightNum; i++)
{
if (i == CurrentPage)
{
OutPut += "<span style='color:red'>" + i.ToString() + "</span> ";
}
else
{
OutPut += "<a href=\"" + PageUrl + "Page=" + i.ToString() + "\">" + i.ToString() + "</a> ";
}
}
if (CurrentPage > 1)
{
OutPut = "<a href='" + PageUrl + "Page=1'>首页</a> <a href=\"" + PageUrl + "Page=" + (CurrentPage - 1) + "\">上一页</a> " + OutPut;
}
if (CurrentPage < PageCount)
{
OutPut += " <a href=\"" + PageUrl + "Page=" + (CurrentPage + 1) + "\">下一页</a> <a href='" + PageUrl + "Page=" + PageCount + "'>末页</a>";
}
Pager.InnerHtml = OutPut;
}
/// <summary>
/// 加载页面
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataBind();
}
}
/// <summary>
/// 绑定 GridView
/// </summary>
protected void DataBind()
{
OleDbCommand cmd;
String sql;
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
// 由于是 Access 数据库,我们只进行简单的分页。对于性能要求较高的地方,请自行采取其他方法。
sql = "SELECT COUNT(*) FROM [Student]";
cmd = new OleDbCommand(sql, cn);
// 总的记录数
int TotalCount = Convert.ToInt32(cmd.ExecuteScalar());
//当前页的序号
int PageIndex = 1;
String page = Request.QueryString["Page"];
if (page == null) page = "1";
Int32.TryParse(page, out PageIndex);
if (PageIndex < 1) PageIndex = 1;
int PageCount = (int)Math.Ceiling((double)(TotalCount) / PageItem);
if (PageIndex > PageCount) PageIndex = PageCount;
int startRecord = (PageIndex - 1) * PageItem;
sql = "SELECT * FROM [Student] ORDER BY [id] DESC";
OleDbDataAdapter da = new OleDbDataAdapter(sql, cn);
DataSet ds = new DataSet();
da.Fill(ds, startRecord, PageItem, "Student");
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
cn.Close();
BuildPagers(TotalCount, PageIndex);
}
</script>
<!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>GridView 插入、删除、修改的例子</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
OnRowDataBound="GridView1_RowDataBound" ShowFooter="true">
<HeaderStyle BackColor="#ccff99" Font-Bold="true" />
<Columns>
<asp:TemplateField HeaderText="姓名">
<ItemTemplate>
<asp:PlaceHolder ID="LabelTitle" runat="server">
<%#Eval("Title") %></asp:PlaceHolder>
<asp:TextBox ID="uTitle" runat="server" Text='<%#Eval("Title") %>' Visible="false"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="NewTitle" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="生日(yyyy-MM-dd格式)">
<ItemTemplate>
<asp:PlaceHolder ID="LabelBirthday" runat="server">
<%#Eval("BirthDay", "{0:yyyy-MM-dd}")%></asp:PlaceHolder>
<asp:TextBox ID="uBirthDay" runat="server" Text='<%#Eval("BirthDay", "{0:yyyy-MM-dd}")%> '
Visible="false" />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="NewBirthDay" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="性别">
<ItemTemplate>
<asp:PlaceHolder ID="LabelGender" runat="server">
<%#(Eval("Gender")).ToString() =="True"?"男":"女"%></asp:PlaceHolder>
<asp:RadioButtonList ID="uGender" runat="server" RepeatDirection="Horizontal" Visible="false">
<asp:ListItem Text="男"></asp:ListItem>
<asp:ListItem Text="女"></asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
<FooterTemplate>
<asp:RadioButtonList ID="NewGender" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Selected="true" Text="男"></asp:ListItem>
<asp:ListItem Text="女"></asp:ListItem>
</asp:RadioButtonList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="年级">
<ItemTemplate>
<asp:PlaceHolder ID="LabelClassName" runat="server">
<%#Eval("ClassName")%></asp:PlaceHolder>
<asp:DropDownList ID="uClassName" runat="server" Visible="false">
<asp:ListItem Text="小学" Value="小学"></asp:ListItem>
<asp:ListItem Text="中学" Value="中学"></asp:ListItem>
<asp:ListItem Text="高中" Value="高中"></asp:ListItem>
<asp:ListItem Text="大学" Value="大学"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="NewClassName" runat="server">
<asp:ListItem Text="小学" Value="小学"></asp:ListItem>
<asp:ListItem Text="中学" Value="中学"></asp:ListItem>
<asp:ListItem Text="高中" Value="高中"></asp:ListItem>
<asp:ListItem Text="大学" Value="大学"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="照片">
<ItemTemplate>
<asp:PlaceHolder ID="LabelPhoto" runat="server">
<%# GetUserPhoto(Eval("PhotoPath")) %></asp:PlaceHolder>
<asp:FileUpload ID="uPhoto" runat="server" Visible="false" />
</ItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="AddPhoto" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="操作">
<ItemTemplate>
<asp:Panel ID="PanelNormal" runat="server">
<asp:Button ID="EditButton" runat="server" Text="修改" OnClick="EditClick" CommandArgument='<%#Eval("id") %>' />
<asp:Button ID="DeleteButton" runat="server" Text="删除" OnClick="DeleteClick" CommandArgument='<%#Eval("id") %>' />
</asp:Panel>
<asp:Panel ID="PanelUpdate" runat="server" Visible="false">
<asp:Button ID="UpdateButton" runat="server" Text="更新" OnClick="UpdateClick" CommandArgument='<%#Eval("id") %>' />
<asp:Button ID="CancelButton" runat="server" Text="取消" OnClick="CancelClick" />
</asp:Panel>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="AddButton" runat="server" Text="添加新纪录" OnClick="AddClick" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<table cellspacing="0" rules="all" border="1" style="border-collapse: collapse;">
<tr>
<th>姓名</th>
<th>生日(yyyy-MM-dd格式)</th>
<th>性别</th>
<th>年级</th>
<th>照片</th>
<th>操作</th>
</tr>
<tr>
<td>
<asp:TextBox ID="NewTitle" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="NewBirthDay" runat="server"></asp:TextBox>
</td>
<td>
<asp:RadioButtonList ID="NewGender" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Selected="true" Text="男"></asp:ListItem>
<asp:ListItem Text="女"></asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:DropDownList ID="NewClassName" runat="server">
<asp:ListItem Text="小学" Value="小学"></asp:ListItem>
<asp:ListItem Text="中学" Value="中学"></asp:ListItem>
<asp:ListItem Text="高中" Value="高中"></asp:ListItem>
<asp:ListItem Text="大学" Value="大学"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:FileUpload ID="AddPhoto" runat="server" />
</td>
<td>
<asp:Button ID="b" runat="server" Text="添加学生" OnClick="AddClick" />
</td>
</tr>
</table>
</EmptyDataTemplate>
</asp:GridView>
<div id="Pager" runat="server" style="text-align:left;padding:10px 0;"></div>
<asp:Label ID="ErrorMsg" runat="server" ForeColor="red"></asp:Label>
</form>
</body>
</html>
//每页显示的记录数
private int PageItem = 10;
private void BuildPagers(int TotalCountRecord, int CurrentPage)
{
int Step = 6;
int LeftNum = 0;
int RightNum = 0;
String PageUrl = "?";
int PageCount = (int)Math.Ceiling((double)(TotalCountRecord) / PageItem);
if (CurrentPage - Step < 1)
{
LeftNum = 1;
}
else
{
LeftNum = CurrentPage - Step;
}
if (CurrentPage + Step > PageCount)
{
RightNum = PageCount;
}
else
{
RightNum = CurrentPage + Step;
}
string OutPut = "";
for (int i = LeftNum; i <= RightNum; i++)
{
if (i == CurrentPage)
{
OutPut += "<span style='color:red'>" + i.ToString() + "</span> ";
}
else
{
OutPut += "<a href=\"" + PageUrl + "Page=" + i.ToString() + "\">" + i.ToString() + "</a> ";
}
}
if (CurrentPage > 1)
{
OutPut = "<a href='" + PageUrl + "Page=1'>首页</a> <a href=\"" + PageUrl + "Page=" + (CurrentPage - 1) + "\">上一页</a> " + OutPut;
}
if (CurrentPage < PageCount)
{
OutPut += " <a href=\"" + PageUrl + "Page=" + (CurrentPage + 1) + "\">下一页</a> <a href='" + PageUrl + "Page=" + PageCount + "'>末页</a>";
}
Pager.InnerHtml = OutPut;
}
/// <summary>
/// 加载页面
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataBind();
}
}
/// <summary>
/// 绑定 GridView
/// </summary>
protected void DataBind()
{
OleDbCommand cmd;
String sql;
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
// 由于是 Access 数据库,我们只进行简单的分页。对于性能要求较高的地方,请自行采取其他方法。
sql = "SELECT COUNT(*) FROM [Student]";
cmd = new OleDbCommand(sql, cn);
// 总的记录数
int TotalCount = Convert.ToInt32(cmd.ExecuteScalar());
//当前页的序号
int PageIndex = 1;
String page = Request.QueryString["Page"];
if (page == null) page = "1";
Int32.TryParse(page, out PageIndex);
if (PageIndex < 1) PageIndex = 1;
int PageCount = (int)Math.Ceiling((double)(TotalCount) / PageItem);
if (PageIndex > PageCount) PageIndex = PageCount;
int startRecord = (PageIndex - 1) * PageItem;
sql = "SELECT * FROM [Student] ORDER BY [id] DESC";
OleDbDataAdapter da = new OleDbDataAdapter(sql, cn);
DataSet ds = new DataSet();
da.Fill(ds, startRecord, PageItem, "Student");
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
cn.Close();
BuildPagers(TotalCount, PageIndex);
}
</script>
<!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>GridView 插入、删除、修改的例子</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
OnRowDataBound="GridView1_RowDataBound" ShowFooter="true">
<HeaderStyle BackColor="#ccff99" Font-Bold="true" />
<Columns>
<asp:TemplateField HeaderText="姓名">
<ItemTemplate>
<asp:PlaceHolder ID="LabelTitle" runat="server">
<%#Eval("Title") %></asp:PlaceHolder>
<asp:TextBox ID="uTitle" runat="server" Text='<%#Eval("Title") %>' Visible="false"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="NewTitle" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="生日(yyyy-MM-dd格式)">
<ItemTemplate>
<asp:PlaceHolder ID="LabelBirthday" runat="server">
<%#Eval("BirthDay", "{0:yyyy-MM-dd}")%></asp:PlaceHolder>
<asp:TextBox ID="uBirthDay" runat="server" Text='<%#Eval("BirthDay", "{0:yyyy-MM-dd}")%> '
Visible="false" />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="NewBirthDay" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="性别">
<ItemTemplate>
<asp:PlaceHolder ID="LabelGender" runat="server">
<%#(Eval("Gender")).ToString() =="True"?"男":"女"%></asp:PlaceHolder>
<asp:RadioButtonList ID="uGender" runat="server" RepeatDirection="Horizontal" Visible="false">
<asp:ListItem Text="男"></asp:ListItem>
<asp:ListItem Text="女"></asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
<FooterTemplate>
<asp:RadioButtonList ID="NewGender" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Selected="true" Text="男"></asp:ListItem>
<asp:ListItem Text="女"></asp:ListItem>
</asp:RadioButtonList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="年级">
<ItemTemplate>
<asp:PlaceHolder ID="LabelClassName" runat="server">
<%#Eval("ClassName")%></asp:PlaceHolder>
<asp:DropDownList ID="uClassName" runat="server" Visible="false">
<asp:ListItem Text="小学" Value="小学"></asp:ListItem>
<asp:ListItem Text="中学" Value="中学"></asp:ListItem>
<asp:ListItem Text="高中" Value="高中"></asp:ListItem>
<asp:ListItem Text="大学" Value="大学"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="NewClassName" runat="server">
<asp:ListItem Text="小学" Value="小学"></asp:ListItem>
<asp:ListItem Text="中学" Value="中学"></asp:ListItem>
<asp:ListItem Text="高中" Value="高中"></asp:ListItem>
<asp:ListItem Text="大学" Value="大学"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="照片">
<ItemTemplate>
<asp:PlaceHolder ID="LabelPhoto" runat="server">
<%# GetUserPhoto(Eval("PhotoPath")) %></asp:PlaceHolder>
<asp:FileUpload ID="uPhoto" runat="server" Visible="false" />
</ItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="AddPhoto" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="操作">
<ItemTemplate>
<asp:Panel ID="PanelNormal" runat="server">
<asp:Button ID="EditButton" runat="server" Text="修改" OnClick="EditClick" CommandArgument='<%#Eval("id") %>' />
<asp:Button ID="DeleteButton" runat="server" Text="删除" OnClick="DeleteClick" CommandArgument='<%#Eval("id") %>' />
</asp:Panel>
<asp:Panel ID="PanelUpdate" runat="server" Visible="false">
<asp:Button ID="UpdateButton" runat="server" Text="更新" OnClick="UpdateClick" CommandArgument='<%#Eval("id") %>' />
<asp:Button ID="CancelButton" runat="server" Text="取消" OnClick="CancelClick" />
</asp:Panel>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="AddButton" runat="server" Text="添加新纪录" OnClick="AddClick" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<table cellspacing="0" rules="all" border="1" style="border-collapse: collapse;">
<tr>
<th>姓名</th>
<th>生日(yyyy-MM-dd格式)</th>
<th>性别</th>
<th>年级</th>
<th>照片</th>
<th>操作</th>
</tr>
<tr>
<td>
<asp:TextBox ID="NewTitle" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="NewBirthDay" runat="server"></asp:TextBox>
</td>
<td>
<asp:RadioButtonList ID="NewGender" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Selected="true" Text="男"></asp:ListItem>
<asp:ListItem Text="女"></asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:DropDownList ID="NewClassName" runat="server">
<asp:ListItem Text="小学" Value="小学"></asp:ListItem>
<asp:ListItem Text="中学" Value="中学"></asp:ListItem>
<asp:ListItem Text="高中" Value="高中"></asp:ListItem>
<asp:ListItem Text="大学" Value="大学"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:FileUpload ID="AddPhoto" runat="server" />
</td>
<td>
<asp:Button ID="b" runat="server" Text="添加学生" OnClick="AddClick" />
</td>
</tr>
</table>
</EmptyDataTemplate>
</asp:GridView>
<div id="Pager" runat="server" style="text-align:left;padding:10px 0;"></div>
<asp:Label ID="ErrorMsg" runat="server" ForeColor="red"></asp:Label>
</form>
</body>
</html>
#4
#5
#6
#7
#8
插入不好实现,要么试试级联更新?
空值更新好解决,
在更新出 where选项 之选定 主键 或者唯一判断一条数据的那个字段就可以 ,把含有NULL的都删掉
空值更新好解决,
在更新出 where选项 之选定 主键 或者唯一判断一条数据的那个字段就可以 ,把含有NULL的都删掉