ASP.NET GridView空间绑定显示数据,启用编辑、删除、增加数据功能,三个功能当中删除功能可能接触频率要多,这个功能也相对容易,触发RowDeleting事件。编辑功能可能稍微要少用,GridView开启编辑数据功能也就触发三个事件RowEditing、RowUpdating和RowCancelingEdit,RowEditing为启动编辑中、RowUpdating为数据编辑操作更新制定行就是在此事件中出发数据库操作,RowCancelingEdit即取消编辑取消编辑状态。增加新数据插入数据通过触发RowCommand的事件完成数据插入。下面是示例最终效果演示。
数据库部分
数据库采用的 ASP.NET MVC深入DropDownList 中的数据源,MyDatabase.mdf 数据库中有两个表一个是产品分类ProductCategories,一个是产品数据Product_Data,两表通过ProductCategoriesId关联。本文采用DataSet数据集操作数据库,DataSetProduct.xsd中可对应的看到两个表的数据查询操作,ProductCategoriesTableAdapter中GetProductCategoriesDataById方法通过ProductCategoriesId来获取ProductCategoriesName,Product_DataTableAdapter中即是Product_Data的增删改查的查询方法(GetProuductData为获取全表,DeleteProductById为删除指定Id的产品,InsertProduct即插入新的产品数据,UpdateProductById更新指定Id的产品数据)。
页面操作部分
前台部分 在页面放入GridView控件,修改GridView的默认属性,在修改列中打开字段面板,将“自动生成字段”钩选取消,添加6列TemplateField(列名分别为产品Id、产品名、产品价格、产品型号、Edit编辑列),另外一列CommandField选取列可有可无,本文也没有对选取列作后处理操作;GridView的自动套用格式选用专业型,编辑状态分别在产品名列、产品价格列、产品型号列的EditItemTemplate放入TextBox宽设为95%,在产品类别中的EditItemTemplate中放入Dropdownlist用以绑定ProductCategories;将GridView的页脚显示ShowFooter设为True,同样分别在产品名列、产品价格列、产品型号列的FooterTemplate放入TextBox宽设为95%,产品类别的FooterTemplate中放入Dropdownlist和一个TextBox将其CSS样式隐藏(这里主要是用来接收Dropdownlist的值,验证是否选取值则是验证TextBox),在Edit列的FooterTemplate中放入一个按钮用以建立新的产品数据,其他四个验证控件用来验证建立数据是否为空,均放在产品Id列的FooterTemplate中,然后在GridView外面加入一个ValidationSummary用来显示验证的详细内容。
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
ShowFooter="True" BorderStyle="Solid"
BorderWidth="1px" BorderColor="#5D7B9D"
AutoGenerateColumns="False" CellPadding="4" EnableModelValidation="True"
Font-Size="14px" DataKeyNames="ProductId"
ForeColor="#333333" GridLines="None"
onpageindexchanging="GridView1_PageIndexChanging"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
onselectedindexchanging="GridView1_SelectedIndexChanging"
onrowcommand="GridView1_RowCommand1" onrowupdating="GridView1_RowUpdating">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:TemplateField HeaderText="产品Id">
<FooterTemplate>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="Txt_ProductName" ErrorMessage="产品名"
ValidationGroup="Create" Text="*"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="Txt_ProductPrice" ErrorMessage="产品价格"
ValidationGroup="Create" Text="*"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
ControlToValidate="Txt_ProductType" ErrorMessage="产品型号"
ValidationGroup="Create" Text="*"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"
ControlToValidate="TextBox4" ErrorMessage="产品类别"
ValidationGroup="Create" Text="*"></asp:RequiredFieldValidator>
</FooterTemplate>
<ItemTemplate><%# Eval("ProductId")%> </ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="产品名">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Width="95%"
Text='<%# Eval("ProductName")%>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="Txt_ProductName" runat="server"
Width="95%" ValidationGroup="Create" />
</FooterTemplate>
<ItemTemplate><%# Eval("ProductName")%> </ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="产品价格">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Width="95%"
Text='<%# Eval("ProductPrice")%>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="Txt_ProductPrice" runat="server"
Width="95%" ValidationGroup="Create" />
</FooterTemplate>
<ItemTemplate><%# Eval("ProductPrice","{0:C}")%>
</ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="产品类型">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Width="95%"
Text='<%# Eval("ProudctType")%>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="Txt_ProductType" runat="server"
Width="95%" ValidationGroup="Create" />
</FooterTemplate>
<ItemTemplate><%# Eval("ProudctType")%> </ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="产品类别">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSource='<%# new _Default().CategoriesData() %>'
DataTextField="ProductCategoriesName"
DataValueField="ProductCategoriesId"
SelectedValue='<%# Eval("ProductCategoriesId") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DropDownList2" runat="server"
DataSource='<%# new _Default().CategoriesData() %>'
DataTextField="ProductCategoriesName"
DataValueField="ProductCategoriesId"
ValidationGroup="Create"/>
<asp:TextBox ID="TextBox4" runat="server"
Width="0px" Height="0px" CssClass="viewFalse" />
</FooterTemplate>
<ItemTemplate>
<%# new _Default().ProductCategoriesName(Convert.ToInt32(
Eval("ProductCategoriesId")))%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton3" runat="server"
CommandName="update">更新</asp:LinkButton>
<asp:LinkButton ID="LinkButton4" runat="server"
CommandName="cancel">取消 </asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="Button1" runat="server" Text="建立"
CommandName="save" ValidationGroup="Create"
onclick="Button1_Click"/>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server"
CommandName="edit">编辑</asp:LinkButton>
<asp:LinkButton ID="LinkButton5" runat="server"
CausesValidation="False" CommandName="Delete" CssClass="btnlink"
OnClientClick="return confirm('是否刪除?无法恢复!!');"
Text="刪除">
</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>
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
ValidationGroup="Create" />
</form>
后台部分 在Default.aspx.cs中将using DataSetProductTableAdapters和using System.Data引入进来,建立私有Product_DataTableAdapter的实例化private Product_DataTableAdapter ProductCenter = new Product_DataTableAdapter();,这样ProductCenter就可以得到Product_Data表的相对应的数据操作方法。同样ProductCategoriesTableAdapter的实例化ProductCategories获取到ProductCategories表相对应的数据操作方法。在Page_Load的!IsPostBack中将ProductCenter.GetProductData()方法绑定给GridView1.DataSource,然后在执行Chanage();方法,Chanage()方法中主要是GridView1.FooterRow.FindControl("DropDownList2")即查找FooterRow中的DropDownList控件,并赋给默认值和加入js脚本事件select(objOption,objTxt)在onchange中响应。在前台GridView中的产品类别中ItemTemplate中通过ProductCategoriesName(int id)获取产品类别名称<%# new _Default().ProductCategoriesName(Convert.ToInt32( Eval("ProductCategoriesId")))%>。在<EditItemTemplate>中让Dropdownlist绑定CategoriesData()让其在编辑状态下绑定ProductCategories的数据<asp:DropDownList ID="DropDownList1" runat="server" DataSource='<%# new _Default().CategoriesData() %>' DataTextField="ProductCategoriesName" DataValueField="ProductCategoriesId" SelectedValue='<%# Eval("ProductCategoriesId") %>' />在<FooterTemplate>中也用同样的方式绑定DropdownList2。
编辑事件 让GridView响应GridView1_RowEditing即编辑状态,GridView1_RowEditing让GridView1.DataSource 再绑定一次ProductCenter.GetProductData(),设为编辑状态GridView1.EditIndex = e.NewEditIndex;,同样执行Chanage();。GridView1_RowCancelingEdit取消编辑只需要GridView1.EditIndex = -1;即可,其它和GridView1_RowEditing相同。GridView1_RowUpdating中更新数据操作,先编辑状态的这一行所有列的值获取到,并且也将这一列得主键值获取到,然后通过ProductCenter.UpdateProductById方法带入这一列得值更新操作,其它的和GridView1_RowCancelingEdit相同。
增加数据操作 通过GridView1_RowCommand1触发,前台Edit列的<FooterTemplate>中Button1的CommandName为save,在这里触发先判断出发的CommandName是否是save,如果是则获取GridView的产品列、产品价格、产品型类型号列、产品类别列<FooterTemplate>的TextBox值后执行ProductCenter.InsertProduct带入TextBox值插入新数据。
删除数据 通过GridView1_RowDeleting事件触发,相对容易先指定删除的这一行得主键获取到GridView1.DataKeys[e.RowIndex].Value并且转化为Int,传给 ProductCenter.Delete方法,在绑定一次GridView和Chanage()执行一次。
分页操作也简单在GridView1_PageIndexChanging中加入GridView1.PageIndex = e.NewPageIndex;即可,其它保持一致。