GridView结合dropdownlist更改父级ID

PS:带有注释部分的内容为实现的关键

 

  
  
  
  
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> 
  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
  4.  
  5. <html xmlns="http://www.w3.org/1999/xhtml"> 
  6. <head runat="server"> 
  7.     <title></title> 
  8. </head> 
  9. <body> 
  10.     <form id="form1" runat="server"> 
  11.     <div> 
  12.         <asp:GridView ID="gvStudent2" runat="server"  AutoGenerateColumns="False"   
  13.             CellPadding="4" ForeColor="#333333" GridLines="None"   
  14.             onrowcancelingedit="gvStudent2_RowCancelingEdit"   
  15.             onrowdatabound="gvStudent2_RowDataBound" onrowdeleting="gvStudent2_RowDeleting"   
  16.             onrowediting="gvStudent2_RowEditing" onrowupdating="gvStudent2_RowUpdating"   
  17.             onselectedindexchanging="gvStudent2_SelectedIndexChanging"   
  18.             onpageindexchanging="gvStudent2_PageIndexChanging" DataKeyNames="id"> 
  19.             <RowStyle BackColor="#EFF3FB" /> 
  20.           
  21.      <Columns> 
  22.     <asp:BoundField HeaderText="编号" Visible="false"  DataField="id"/>   
  23.          
  24.         <asp:TemplateField HeaderText ="姓名"> 
  25.         <ItemTemplate> 
  26.          <%#Eval("name")%> 
  27.         </ItemTemplate> 
  28.         <EditItemTemplate> 
  29.          <asp:textbox ID ="TBName" Text='<%#Eval("name") %>' runat="server">'> 
  30.          </asp:textbox> 
  31.         </EditItemTemplate> 
  32.         </asp:TemplateField>         
  33.       
  34.            
  35.         <asp:TemplateField HeaderText ="父级" > 
  36.         <ItemTemplate> 
  37.             <%#Eval("PName") %> 
  38.         </ItemTemplate> 
  39.         <EditItemTemplate> 
  40.            <asp:HiddenField ID="HDFParentStu" runat="server" Value='<%# Eval("PId") %>' /><%--存储实际要操作的字段 --%> 
  41.            <asp:DropDownList ID="DDLParentStu" runat="server" Width="90px" /> 
  42.         </EditItemTemplate>          
  43.         </asp:TemplateField>       
  44.            
  45.          <asp:CommandField ShowEditButton="True" /> 
  46.          <asp:CommandField ShowDeleteButton="True" /> 
  47.            
  48.         </Columns>        
  49.               <PagerSettings FirstPageText="" LastPageText="" NextPageText="" PreviousPageText="" /> 
  50.                             <RowStyle Height="20px" BackColor="#F7F6F3" ForeColor="#333333" /> 
  51.                             <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> 
  52.                             <EditRowStyle BackColor="#999999" /> 
  53.                             <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> 
  54.                             <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> 
  55.                             <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> 
  56.                             <AlternatingRowStyle BackColor="White" ForeColor="#284775" />            
  57.         </asp:GridView> 
  58.    
  59.     </div> 
  60.     </form> 
  61. </body> 
  62. </html> 

C#代码

  
  
  
  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Configuration;  
  8. using System.Data;  
  9. using System.Data.SqlClient;  
  10. using System.Collections;  
  11.  
  12. public partial class Default2 : System.Web.UI.Page  
  13. {  
  14.     protected void Page_Load(object sender, EventArgs e)  
  15.     {  
  16.         if (!IsPostBack)//首次加载和访问,ispostback=true 表示为相应客户端回发而加载  
  17.             GridViewBind();       
  18.     }  
  19.  
  20.     protected void gvStudent2_PageIndexChanging(object sender, GridViewPageEventArgs e)  
  21.     {  
  22.         gvStudent2.PageIndex = e.NewPageIndex;//当前显示页的索引  
  23.         GridViewBind();  
  24.     }  
  25.     protected void gvStudent2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  26.     {  
  27.         gvStudent2.EditIndex = -1;  
  28.         GridViewBind();  
  29.     }  
  30.     protected void gvStudent2_RowDataBound(object sender, GridViewRowEventArgs e)  
  31.     {  
  32.         string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();  
  33.        //绑定dropdownlist 的值  
  34.         if (((DropDownList)e.Row.FindControl("DDLParentStu")) != null)  
  35.         {  
  36.             DropDownList DDLParentStu = (DropDownList)e.Row.FindControl("DDLParentStu");  
  37.  
  38.             string sqlStr = "select id as Pid,name as PName from Category"; //取本表中的 id 、name 作为父ID、父name的集合  
  39.             DataSet ds = new DataSet();  
  40.             SqlConnection conn = new SqlConnection(StrConn);  
  41.  
  42.             conn.Open();  
  43.             SqlDataAdapter da = new SqlDataAdapter(sqlStr, conn);  
  44.             da.Fill(ds);  
  45.             conn.Close();              
  46.  
  47.             DDLParentStu.DataSource = ds.Tables[0].DefaultView;//从库中获取数据  
  48.             DDLParentStu.DataTextField = "PName";//列表项提供文本内容的数据源字段 (显示在dropdownlist的可见文本)  
  49.             DDLParentStu.DataValueField = "Pid";//各列表项提供值的数据源字段   (实际要操控的字段)  
  50.             DDLParentStu.DataBind();  
  51.  
  52.             DDLParentStu.SelectedValue = ((HiddenField)e.Row.FindControl("HDFParentStu")).Value; //Pid 与 PName 的完美结合  
  53.         }     
  54.       
  55.          
  56.     }  
  57.     protected void gvStudent2_RowDeleting(object sender, GridViewDeleteEventArgs e)  
  58.     {  
  59.         string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();  
  60.  
  61.         string id = gvStudent2.DataKeys[e.RowIndex].Values[0].ToString();  
  62.         string sql = "delete from student where id=" + id;  
  63.  
  64.         try  
  65.         {  
  66.             SqlConnection conn = new SqlConnection(StrConn);  
  67.             if (conn.State.ToString() == "Closed") conn.Open();  
  68.             SqlCommand comm = new SqlCommand(sql, conn);  
  69.             comm.ExecuteNonQuery();  
  70.             comm.Dispose();  
  71.             if (conn.State.ToString() == "Open") conn.Close();  
  72.  
  73.             gvStudent2.EditIndex = -1;  
  74.             GridViewBind();  
  75.         }  
  76.         catch (Exception ex)  
  77.         {  
  78.             Response.Write("数据库错误,错误原因:" + ex.Message);  
  79.             Response.End();  
  80.         }  
  81.  
  82.     }  
  83.     protected void gvStudent2_RowEditing(object sender, GridViewEditEventArgs e)  
  84.     {  
  85.         gvStudent2.EditIndex = e.NewEditIndex;//所编辑行的索引  
  86.         GridViewBind();  
  87.     }  
  88.     protected void gvStudent2_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  89.     {  
  90.         string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();  
  91.         try  
  92.         {  
  93.                    
  94.             string id = ((GridView)sender).DataKeys[e.RowIndex].Values["id"].ToString();  
  95.  
  96.             string name = ((TextBox)gvStudent2.Rows[e.RowIndex].FindControl("TBName")).Text;       
  97.  
  98.  
  99.             int ParentId = Convert.ToInt32(((DropDownList)gvStudent2.Rows[e.RowIndex].FindControl("DDLParentStu")).SelectedValue);//获取选中的父级名字对应的父ID  
  100.             SqlConnection conn = new SqlConnection(StrConn);  
  101.  
  102.             conn.Open();  
  103.  
  104.             string sql = "update Category set  name='" + name + "', parentId=" + ParentId + "  where id=" + id;  //更改当前表中的 name 以及 父ID  
  105.              
  106.  
  107.             SqlCommand cmd = new SqlCommand(sql, conn);  
  108.             cmd.ExecuteNonQuery();  
  109.             cmd.Dispose();  
  110.             if (conn.State.ToString() == "open")  
  111.                 conn.Close();  
  112.  
  113.             gvStudent2.EditIndex = -1;  
  114.             GridViewBind();  
  115.         }  
  116.         catch (Exception ex)  
  117.         {  
  118.             Response.Write("数据库错误,错误原因:" + ex.Message);  
  119.             Response.End();  
  120.         }  
  121.     }  
  122.     protected void gvStudent2_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)  
  123.     {  
  124.  
  125.     }  
  126.  
  127.     private void GridViewBind()  
  128.     {  
  129.         string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();    //在web.config中定义过了connectionString  
  130.       
  131.         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,将对应的父级名字显示出  
  132.         DataSet ds = new DataSet();  
  133.         try  
  134.         {  
  135.             SqlConnection conn = new SqlConnection(StrConn);  
  136.  
  137.             conn.Open();  
  138.             SqlDataAdapter da = new SqlDataAdapter(sqlStr, conn);  
  139.             da.Fill(ds);  
  140.             conn.Close();  
  141.             DataTable tb = ds.Tables[0];  
  142.  
  143.             gvStudent2.DataSource = tb;  
  144.             gvStudent2.DataBind();  
  145.         }  
  146.         catch (Exception ex)  
  147.         {  
  148.             Response.Write("数据库错误,错误原因:" + ex.Message);  
  149.             Response.End();  
  150.         }  
  151.  
  152.     }  
  153. }  

 

web.config 中的配置

 

 

你可能感兴趣的:(职场,休闲)