GridView增删改查新弄法
GridView增删改查新玩法
后台代码:
这样你就可以只显示一部分比较重要的数据,当需要编辑或者查看数据的详情时,跳转到另外一个页面进行操作~
GridView是在web页面中显示数据源中的数据,将数据源中的一行数据,也就是一条记录,显示为在web页面上输出表格中的一行.方便我们对数据的增删改查~
以前用GridView的时候,编辑数据总是在表格里面进行编辑,设想我们创建的实体的字段较多时,一般会在GridView显示一部分字段,但有可能编辑其他没显示的字段,因此我们需要一个单独的页面。
前台代码:
<div> <asp:TextBox ID="txtUser" runat="server"></asp:TextBox> <asp:Button ID="btnSeek" runat="server" Height="21px" OnClick="btnSeek_Click" Text="查询" Width="86px" /> <br /> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"> <Columns> <asp:TemplateField HeaderText="用户名"> <ItemTemplate> <asp:Label ID="Label2" runat="server" Text='<%# Bind("userName") %>' ToolTip='<%# Bind("userName") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="邮箱"> <ItemTemplate> <asp:Label ID="Label3" runat="server" Text='<%# Bind("userEmail") %>' ToolTip='<%# Bind("userEmail") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="管理" ShowHeader="False"> <ItemTemplate> <asp:LinkButton ID="btnEdit" runat="server" CausesValidation="False" OnClick="btnEdit_Click" CommandArgument='<%# Bind("id") %>' Text="编辑"></asp:LinkButton> <asp:LinkButton ID="btnDelete" runat="server" CausesValidation="False" OnClick="btnDelete_Click" CommandArgument='<%# Bind("id") %>' Text="删除"></asp:LinkButton> <asp:LinkButton ID="btnDetail" runat="server" CausesValidation="false" OnClick="btnDetail_Click" CommandArgument='<%# Bind("id") %>' Text="详情"> </asp:LinkButton> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </div>
后台代码:
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { InitData(txtUser.Text.Trim()); } } private void InitData(string userName) { ProductEntities db = new ProductEntities(); var user = from A in db.T_User select new { id = A.User_ID, userName = A.User_Name, userEmail = A.User_EMail }; if (!string.IsNullOrEmpty(userName)) { user = user.Where(p=>p.userName.Contains(userName)); } this.GridView1.DataSource = user; this.GridView1.DataBind(); } protected void btnSeek_Click(object sender, EventArgs e) { InitData(txtUser.Text.Trim());//多个条件查询时可扩展 } protected void btnEdit_Click(object sender, EventArgs e) { _Redirct(sender, "GridViewTestEdit.aspx?id={0}"); } protected void btnDelete_Click(object sender, EventArgs e) { int id = Convert.ToInt32((sender as LinkButton).CommandArgument); } protected void btnDetail_Click(object sender, EventArgs e) { _Redirct(sender, "GridViewTestDetail.aspx?id={0}"); } private void _Redirct(object sender, string url) { int id = Convert.ToInt32((sender as LinkButton).CommandArgument); Response.Redirect(string.Format(url, id)); }
这样你就可以只显示一部分比较重要的数据,当需要编辑或者查看数据的详情时,跳转到另外一个页面进行操作~