PS:带有注释部分的内容为实现的关键
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
- <!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>
- <asp:GridView ID="gvStudent2" runat="server" AutoGenerateColumns="False"
- CellPadding="4" ForeColor="#333333" GridLines="None"
- onrowcancelingedit="gvStudent2_RowCancelingEdit"
- onrowdatabound="gvStudent2_RowDataBound" onrowdeleting="gvStudent2_RowDeleting"
- onrowediting="gvStudent2_RowEditing" onrowupdating="gvStudent2_RowUpdating"
- onselectedindexchanging="gvStudent2_SelectedIndexChanging"
- onpageindexchanging="gvStudent2_PageIndexChanging" DataKeyNames="id">
- <RowStyle BackColor="#EFF3FB" />
- <Columns>
- <asp:BoundField HeaderText="编号" Visible="false" DataField="id"/>
- <asp:TemplateField HeaderText ="姓名">
- <ItemTemplate>
- <%#Eval("name")%>
- </ItemTemplate>
- <EditItemTemplate>
- <asp:textbox ID ="TBName" Text='<%#Eval("name") %>' runat="server">'>
- </asp:textbox>
- </EditItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText ="父级" >
- <ItemTemplate>
- <%#Eval("PName") %>
- </ItemTemplate>
- <EditItemTemplate>
- <asp:HiddenField ID="HDFParentStu" runat="server" Value='<%# Eval("PId") %>' /><%--存储实际要操作的字段 --%>
- <asp:DropDownList ID="DDLParentStu" runat="server" Width="90px" />
- </EditItemTemplate>
- </asp:TemplateField>
- <asp:CommandField ShowEditButton="True" />
- <asp:CommandField ShowDeleteButton="True" />
- </Columns>
- <PagerSettings FirstPageText="" LastPageText="" NextPageText="" PreviousPageText="" />
- <RowStyle Height="20px" BackColor="#F7F6F3" ForeColor="#333333" />
- <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
- <EditRowStyle BackColor="#999999" />
- <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
- <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
- <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
- <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
- </asp:GridView>
- </div>
- </form>
- </body>
- </html>
C#代码
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- using System.Collections;
- public partial class Default2 : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)//首次加载和访问,ispostback=true 表示为相应客户端回发而加载
- GridViewBind();
- }
- protected void gvStudent2_PageIndexChanging(object sender, GridViewPageEventArgs e)
- {
- gvStudent2.PageIndex = e.NewPageIndex;//当前显示页的索引
- GridViewBind();
- }
- protected void gvStudent2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
- {
- gvStudent2.EditIndex = -1;
- GridViewBind();
- }
- protected void gvStudent2_RowDataBound(object sender, GridViewRowEventArgs e)
- {
- string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();
- //绑定dropdownlist 的值
- if (((DropDownList)e.Row.FindControl("DDLParentStu")) != null)
- {
- DropDownList DDLParentStu = (DropDownList)e.Row.FindControl("DDLParentStu");
- string sqlStr = "select id as Pid,name as PName from Category"; //取本表中的 id 、name 作为父ID、父name的集合
- DataSet ds = new DataSet();
- SqlConnection conn = new SqlConnection(StrConn);
- conn.Open();
- SqlDataAdapter da = new SqlDataAdapter(sqlStr, conn);
- da.Fill(ds);
- conn.Close();
- DDLParentStu.DataSource = ds.Tables[0].DefaultView;//从库中获取数据
- DDLParentStu.DataTextField = "PName";//列表项提供文本内容的数据源字段 (显示在dropdownlist的可见文本)
- DDLParentStu.DataValueField = "Pid";//各列表项提供值的数据源字段 (实际要操控的字段)
- DDLParentStu.DataBind();
- DDLParentStu.SelectedValue = ((HiddenField)e.Row.FindControl("HDFParentStu")).Value; //Pid 与 PName 的完美结合
- }
- }
- protected void gvStudent2_RowDeleting(object sender, GridViewDeleteEventArgs e)
- {
- string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();
- string id = gvStudent2.DataKeys[e.RowIndex].Values[0].ToString();
- string sql = "delete from student where id=" + id;
- try
- {
- SqlConnection conn = new SqlConnection(StrConn);
- if (conn.State.ToString() == "Closed") conn.Open();
- SqlCommand comm = new SqlCommand(sql, conn);
- comm.ExecuteNonQuery();
- comm.Dispose();
- if (conn.State.ToString() == "Open") conn.Close();
- gvStudent2.EditIndex = -1;
- GridViewBind();
- }
- catch (Exception ex)
- {
- Response.Write("数据库错误,错误原因:" + ex.Message);
- Response.End();
- }
- }
- protected void gvStudent2_RowEditing(object sender, GridViewEditEventArgs e)
- {
- gvStudent2.EditIndex = e.NewEditIndex;//所编辑行的索引
- GridViewBind();
- }
- protected void gvStudent2_RowUpdating(object sender, GridViewUpdateEventArgs e)
- {
- string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();
- try
- {
- string id = ((GridView)sender).DataKeys[e.RowIndex].Values["id"].ToString();
- string name = ((TextBox)gvStudent2.Rows[e.RowIndex].FindControl("TBName")).Text;
- int ParentId = Convert.ToInt32(((DropDownList)gvStudent2.Rows[e.RowIndex].FindControl("DDLParentStu")).SelectedValue);//获取选中的父级名字对应的父ID
- SqlConnection conn = new SqlConnection(StrConn);
- conn.Open();
- string sql = "update Category set name='" + name + "', parentId=" + ParentId + " where id=" + id; //更改当前表中的 name 以及 父ID
- SqlCommand cmd = new SqlCommand(sql, conn);
- cmd.ExecuteNonQuery();
- cmd.Dispose();
- if (conn.State.ToString() == "open")
- conn.Close();
- gvStudent2.EditIndex = -1;
- GridViewBind();
- }
- catch (Exception ex)
- {
- Response.Write("数据库错误,错误原因:" + ex.Message);
- Response.End();
- }
- }
- protected void gvStudent2_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
- {
- }
- private void GridViewBind()
- {
- string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString(); //在web.config中定义过了connectionString
- string sqlStr = "select A.id,A.name,A.parentId as Pid,B.name as PName from Category A inner join Category B on a.parentId=b.id"; //自身连接,通过本表中绑定的父ID,将对应的父级名字显示出
- DataSet ds = new DataSet();
- try
- {
- SqlConnection conn = new SqlConnection(StrConn);
- conn.Open();
- SqlDataAdapter da = new SqlDataAdapter(sqlStr, conn);
- da.Fill(ds);
- conn.Close();
- DataTable tb = ds.Tables[0];
- gvStudent2.DataSource = tb;
- gvStudent2.DataBind();
- }
- catch (Exception ex)
- {
- Response.Write("数据库错误,错误原因:" + ex.Message);
- Response.End();
- }
- }
- }
web.config 中的配置