首页 > 下载 > 下载详文:ASP.NET DetailsView编辑增加数据

ASP.NET DetailsView编辑增加数据

发布时间:2012年10月04日 08时03分12秒   属性:程序Web开发 > Microsoft    访问次数:8424
字体: 初始 添加收藏 分享给好友

ASP.NET DetailsView编辑增加数据

ASP.NET中的DetailsView通常用来显示某条数据的详细内容,一般和其它数据控件GridView或Datalist关联结合使用,通过选取GridView或Datalist的某行数据,关联DatailsView来显示详细数据。本文结合ASP.NET GridView编辑增加新数据 中基本结构,采用Gridview 显示所有数据,通过DetailsView来编辑更新、增加插入新数据。数据库部分完全和前面一文一致在本文不做数据库的数据表详细描述,不熟悉的话可以参阅ASP.NET GridView编辑增加新数据中的“数据库部分”。

在前台aspx前台放入GridView和DetailsView两个主要数据控件,将GridView绑定数据以外,加入选择和删除列用以选择和删除指定某行数据。DetailsView将DefaultMode的默认模式设置为"Insert"插入数据模式。 在编辑模式<EditItemTemplate>和插入数据模式<InsertItemTemplate>中的控件放入同样的控件基本保持相同,在插入数据模式下ProductId产品Id是自动由数据库自动增长生成;产品类别ProductCategoriesId列用DropDownList绑定CategoriesData(), 指定DataTextField和DataValueField,DataTextField="ProductCategoriesName" DataValueField="ProductCategoriesId",如果是在编辑模式下还需要指定SelectedValue(SelectedValue='<%# Eval("ProductCategoriesId") %>'),DropDownList 绑定数据列之后再加入一列放入三个Linkbutton,分别用来更新数据、更新数据以及取消操作。为了更好的客户端体验效果,在GridView和DetailsView外面嵌套AJAX控件UpdatePanel,加入ScriptManager控件。下面是前台代码。

HTML 代码  复制
<%@ Page Language="C#" CodeFile="GridViewByDetailView.aspx.cs" AutoEventWireup="true" Inherits="GridViewByDetailView" %> <%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TagPrefix="asp" %> <!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>ASP.NET DetailsView编辑增加数据|遺昕 - weisim3.com</title> <style type="text/css"> .viewFalse { display: none; } </style> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:GridView ID="GridView1" runat="server" AllowPaging="True" CellPadding="4" DataKeyNames="ProductId" EnableModelValidation="True" ForeColor="#333333" AutoGenerateColumns="False" GridLines="None" OnPageIndexChanging="GridView1_PageIndexChanging" OnSelectedIndexChanging="GridView1_SelectedIndexChanging" Width="800px" OnRowDeleting="GridView1_RowDeleting"> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> <Columns> <asp:CommandField ShowSelectButton="True" /> <asp:TemplateField HeaderText="产品Id"> <FooterTemplate> </FooterTemplate> <ItemTemplate> <%# Eval("ProductId")%> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="产品名"> <EditItemTemplate> <asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("ProductName")%>' Width="95%" /> </EditItemTemplate> <FooterTemplate> <asp:TextBox ID="Txt_ProductName" runat="server" ValidationGroup="Create" Width="95%" /> </FooterTemplate> <ItemTemplate> <%# Eval("ProductName")%> </ItemTemplate> <ItemStyle HorizontalAlign="Center" /> </asp:TemplateField> <asp:TemplateField HeaderText="产品价格"> <EditItemTemplate> <asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("ProductPrice")%>' Width="95%" /> </EditItemTemplate> <FooterTemplate> <asp:TextBox ID="Txt_ProductPrice" runat="server" ValidationGroup="Create" Width="95%" /> </FooterTemplate> <ItemTemplate> <%# Eval("ProductPrice","{0:C}")%> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="产品类型"> <EditItemTemplate> <asp:TextBox ID="TextBox3" runat="server" Text='<%# Eval("ProudctType")%>' Width="95%" /> </EditItemTemplate> <FooterTemplate> <asp:TextBox ID="Txt_ProductType" runat="server" ValidationGroup="Create" Width="95%" /> </FooterTemplate> <ItemTemplate> <%# Eval("ProudctType")%> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="产品类别"> <EditItemTemplate> </EditItemTemplate> <FooterTemplate> <asp:TextBox ID="TextBox4" runat="server" CssClass="viewFalse" Height="0px" Width="0px" /> </FooterTemplate> <ItemTemplate> <%# new GridViewByDetailView(). ProductCategoriesName(Convert.ToInt32( Eval("ProductCategoriesId")))%> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Delete"> <ItemTemplate> <asp:LinkButton ID="LinkButton5" runat="server" CausesValidation="False" CommandName="Delete" CssClass="btnlink" Text="刪除" OnClientClick="return confirm('是否刪除?无法恢复!!');" > </asp:LinkButton> </ItemTemplate> </asp:TemplateField> </Columns> <EditRowStyle BackColor="#999999" /> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> </asp:GridView> <div style="width: 800px; background-color: #003366"> <div style="padding: 3px"> <asp:Label ID="Lbl_Product" ForeColor="#66CCFF" runat="server" Font-Bold="True"></asp:Label> </div> </div> <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" CellPadding="4" DefaultMode="Insert" EnableModelValidation="True" ForeColor="#333333" GridLines="None" Height="50px" OnModeChanging="DetailsView1_ModeChanging" Width="800px"> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> <CommandRowStyle BackColor="#E2DED6" Font-Bold="True" /> <EditRowStyle BackColor="#999999" /> <FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" /> <Fields> <asp:TemplateField HeaderText="ProductId"> <EditItemTemplate> <asp:TextBox ID="TextBox2" runat="server" Enabled="false" Text='<%# Bind("ProductId") %>'> </asp:TextBox> </EditItemTemplate> <InsertItemTemplate> <asp:TextBox ID="TextBox2" runat="server" Enabled="false" Text="自动ID"></asp:TextBox> </InsertItemTemplate> <ItemTemplate> <asp:Label ID="Label2" runat="server" Text='<%# Bind("ProductId") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="ProductName"> <EditItemTemplate> <asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("ProductName") %>'></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox5" ErrorMessage="产品名" Text="*"> </asp:RequiredFieldValidator> </EditItemTemplate> <InsertItemTemplate> <asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("ProductName") %>'></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox5" ErrorMessage="产品名" Text="*"> </asp:RequiredFieldValidator> </InsertItemTemplate> <ItemTemplate> <asp:Label ID="Label5" runat="server" Text='<%# Bind("ProductName") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="ProductPrice"> <EditItemTemplate> <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("ProductPrice") %>'></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox4" ErrorMessage="产品价格" Text="*"> </asp:RequiredFieldValidator> </EditItemTemplate> <InsertItemTemplate> <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("ProductPrice") %>'></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox4" ErrorMessage="产品价格" Text="*"> </asp:RequiredFieldValidator> </InsertItemTemplate> <ItemTemplate> <asp:Label ID="Label4" runat="server" Text='<%# Bind("ProductPrice") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="ProudctType"> <EditItemTemplate> <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("ProudctType") %>' Width="400"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="TextBox3" ErrorMessage="产品类别" Text="*"> </asp:RequiredFieldValidator> </EditItemTemplate> <InsertItemTemplate> <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("ProudctType") %>' Width="400"> </asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="TextBox3" ErrorMessage="产品类别" Text="*"> </asp:RequiredFieldValidator> </InsertItemTemplate> <ItemTemplate> <asp:Label ID="Label3" runat="server" Text='<%# Bind("ProudctType") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="ProductCategoriesId"> <EditItemTemplate> <asp:DropDownList ID="DropDownList2" runat="server" DataSource="<%# new GridViewByDetailView().CategoriesData() %>" DataTextField="ProductCategoriesName" DataValueField="ProductCategoriesId" SelectedValue='<%# Eval("ProductCategoriesId") %>' /> </EditItemTemplate> <InsertItemTemplate> <asp:DropDownList ID="DropDownList2" runat="server" DataSource="<%# new GridViewByDetailView().CategoriesData() %>" DataTextField="ProductCategoriesName" AutoPostBack="true" DataValueField="ProductCategoriesId" ValidationGroup="Create" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" /> <asp:TextBox ID="Txt_ProductCategoriesName" runat="server" CssClass="viewFalse" /> <asp:RequiredFieldValidator ID="RequiredFieldValidatorCategoriesName" runat="server" ControlToValidate="Txt_ProductCategoriesName" ErrorMessage="产品类别" Text="*"></asp:RequiredFieldValidator> </InsertItemTemplate> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text=' <%# new GridViewByDetailView().ProductCategoriesName(Convert.ToInt32( Eval("ProductCategoriesId")))%>' /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField ShowHeader="False"> <EditItemTemplate> <asp:LinkButton ID="LikBtn_Update" ForeColor="White" runat="server" CausesValidation="True" Font-Bold="true" Text="更新" OnClick="LikBtn_Update_Click"></asp:LinkButton> <asp:LinkButton ID="LikBtn_Create" ForeColor="White" runat="server" CausesValidation="True" Font-Bold="true" Text="插入" OnClick="LikBtn_Create_Click"> </asp:LinkButton> &nbsp;<asp:LinkButton ID="LinkButton2" ForeColor="White" runat="server" CausesValidation="False" CommandName="Cancel" OnClick="LinkButton2_Click" Font-Bold="true" Text="取消"> </asp:LinkButton> </EditItemTemplate> <ItemTemplate> <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="编辑"> </asp:LinkButton> </ItemTemplate> <FooterStyle BorderColor="#3333CC" /> <ItemStyle BackColor="#003366" BorderColor="White" HorizontalAlign="Left" /> </asp:TemplateField> </Fields> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> </asp:DetailsView> <br /> <asp:Label ID="Label6" runat="server"></asp:Label> </ContentTemplate> </asp:UpdatePanel> </div> </form> </body> </html>

DetailsView触发OnModeChanging,这是DetailsView启用编辑插入数据必须触发的一个属性。GridView触发OnSelectedIndexChanging事件用来选取行数据触发,当GridView选取时即触发让DetailsView1切换到DetailsViewMode.Edit编辑模式;同时需要获取选定行的主键Id值,然后将值传给DetailsView1绑定数据的方法中ProductCenter.GetDataByProductId(Id)。

私有变量private bool isSelect当GridView触发OnSelectedIndexChanging选取时isSelect赋值为True,反之则为False,即当GridView选取时DetailsView进入了编辑模式,未选取时则DetailsView为插入数据模式, 私有方法 private void isCreateOrEdit()用来控制显示更新和插入两Linkbutton,当private bool isSelect为True时更新LikBtn_Update则显示提供更新数据操作, 反之则显示插入数据LikBtn_Create提供数据插入操作。下面是后台关键操作代码展示。

C# 代码  复制
private bool isSelect; protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e) { //Select GridView选取数据 int Id = Convert.ToInt32(GridView1.DataKeys[e.NewSelectedIndex].Value); ViewState["ProductId"] = Id; DetailsView1.ChangeMode(DetailsViewMode.Edit); DetailsView1.DataSource = ProductCenter.GetDataByProductId(Id); DetailsView1.DataBind(); isSelect = true; isCreateOrEdit(); // Chanage(); } protected void DetailsView1_ModeChanging(object sender, DetailsViewModeEventArgs e) { DetailsView1.ChangeMode(e.NewMode); int Id = Convert.ToInt32(ViewState["ProductId"]); DetailsView1.DataSource = ProductCenter.GetDataByProductId(Id); DetailsView1.DataBind(); Chanage(); isCreateOrEdit(); } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { int Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value); //Delete try { ProductCenter.Delete(Id); Label6.Text = "删除成功!"; } catch (Exception err) { Label6.Text = err.ToString(); } GridView1.DataSource = ProductCenter.GetProductData(); GridView1.DataBind(); LinkButton2_Click(sender, e); } protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e) { ((TextBox)DetailsView1.FindControl("Txt_ProductCategoriesName")).Text = ((DropDownList)DetailsView1.FindControl("DropDownList2")).SelectedValue; } protected void LinkButton2_Click(object sender, EventArgs e) { //Insert DetailsViewMode.Insert DetailsView1.ChangeMode(DetailsViewMode.Insert); int Id = Convert.ToInt32(ViewState["ProductId"]); DetailsView1.DataSource = ProductCenter.GetDataByProductId(Id); DetailsView1.DataBind(); Chanage(); isSelect = false; GridView1.SelectedIndex = -1; isCreateOrEdit(); } private void isCreateOrEdit() { if (isSelect) { //编辑 ((LinkButton)DetailsView1.FindControl("LikBtn_Update")).Visible = true; ((LinkButton)DetailsView1.FindControl("LikBtn_Create")).Visible = false; Lbl_Product.Text = "编辑产品"; } else { //新建 ((LinkButton)DetailsView1.FindControl("LikBtn_Create")).Visible = true; ((LinkButton)DetailsView1.FindControl("LikBtn_Update")).Visible = false; Lbl_Product.Text = "新建产品"; } } protected void LikBtn_Update_Click(object sender, EventArgs e) { //Update编辑 DataKey key = DetailsView1.DataKey; TextBox ProductName = (TextBox)DetailsView1.FindControl("TextBox5"); TextBox ProductPrice = (TextBox)DetailsView1.FindControl("TextBox4"); TextBox ProductType = (TextBox)DetailsView1.FindControl("TextBox3"); DropDownList dropCategories = ((DropDownList)DetailsView1.FindControl("DropDownList2")); int ProductCategories = Convert.ToInt32(dropCategories.SelectedValue); int ProductId = Convert.ToInt32(ViewState["ProductId"].ToString()); try { ProductCenter.UpdateProductById(ProductName.Text, Convert.ToDecimal(ProductPrice.Text), ProductType.Text, ProductCategories, ProductId); Label6.Text = "更新成功!"; } catch (Exception err) { Label6.Text = err.ToString(); } GridView1.DataSource = ProductCenter.GetProductData(); GridView1.DataBind(); DetailsView1.DataSource = ProductCenter.GetDataByProductId(ProductId); DetailsView1.DataBind(); isSelect = true; isCreateOrEdit(); } protected void LikBtn_Create_Click(object sender, EventArgs e) { //新建 TextBox ProductName = (TextBox)DetailsView1.FindControl("TextBox5"); TextBox ProductPrice = (TextBox)DetailsView1.FindControl("TextBox4"); TextBox ProductType = (TextBox)DetailsView1.FindControl("TextBox3"); DropDownList dropCategories = ((DropDownList)DetailsView1.FindControl("DropDownList2")); int ProductCategoriesId = Convert.ToInt32(dropCategories.SelectedValue); try { ProductCenter.InsertProduct(ProductName.Text, Convert.ToDecimal(ProductPrice.Text), ProductType.Text, ProductCategoriesId); Label6.Text = "新建“" + ProductName.Text + "/" + Convert.ToDecimal(ProductPrice.Text).ToString("C") + "”成功!"; } catch (Exception err) { Label6.Text = err.ToString(); } GridView1.DataSource = ProductCenter.GetProductData(); GridView1.DataBind(); LinkButton2_Click(sender, e); }

其它GridView分页OnPageIndexChanging、删除OnRowDeleting事件和ASP.NET GridView编辑增加新数据示例文章一致在这里不作描述。本文处除了加入了DetailsView关联操作以外,项目还修改为.NET3.5环境,如果是在上个项目文件编写本文示例,需要在“解决反感资源管理器”中右键网站项目“属性页(Y)”,然后再“生成”的“目标Framework”中下拉选取“.NET Framework3.5”或更高版本。

免费
ASP.NET DetailsView编辑增加数据 (10)
本下载连接不支持第三下载工具打开,请直接点击下载即可
遺昕 | Weisim3.com 下载许可条款 ( 您必须接受同意才可下载 ) .
×
帐号登入 - 遺昕 | Weisim3.com
用 户 名:
用户密码:
注册用户   忘记密码  帮助

登录 Weisim3.com

享受 网络 无纸化 学习

伴随着您成长 伴随着您进步