为了能编辑数据。我在gridview的edititemtemplate加了个dropdownlist,这样,点击编辑时就出现dropdownlist,问题是点击后不知道怎么保存。现在就想问外面怎么访问到这个gridview中dropdownlist控件。不会要加dropdownlist的SelectedIndexChanged事件吧。那样好恶。应该可以让sqldatasouce访问这个dropdownlist。问题是外部的sqldatasource访问不到这个在gridview内部的dropdownlist。

解决方案 »

  1.   

    (DropDownList)GridView1.FindControl("dropdownlist1")这样即可
      

  2.   

    晕。。这个是在CS页面得到内部的控件。。我是想在
     <SelectParameters>
     <asp:ControlParameter ControlID="DropDownList1" Name="role_id" PropertyName="SelectedValue" />
     </SelectParameters>
    这里边访问到dropdownlist1。不知道代码怎么写。上面这段代码是在sqldatasource里边的。要是dropdownlist1是在外部那这样写就没错。但是dropdownlist1是在gridview的edititemtemplate里边。就不知道怎么写了。
      

  3.   

    我再问简单点。。就是怎么样写这个ControlID,直接写DropDownList1会出错。
    ControlParameter country =
      new ControlParameter("country", TypeCode.String, GridView1.TemplateControl.FindControl("DropDownList1").ToString(), "SelectedValue");
          SqlDataSource1.SelectParameters.Add(country);也不行。。帮个忙吧。
      

  4.   

    在编辑列事件中:
    ------------------------------
    DropDownList ddl=(DropDownList)sender;
    string str=ddl.SelectItem.Text;
      

  5.   

    这样写的时候要不行  你把ddl的autopostback属性设置成true试试
      

  6.   

    或者这样:(在编辑列事件中)
    -------------------------------
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridViewRow gvr = GridView1.Rows[e.NewEditIndex];
            DropDownList ddl = gvr.Cells[4].Controls[0] as DropDownList;
            //or
            DropDownList ddl1 = gvr.FindControl("DropDownList1") as DropDownList;
        }
      

  7.   

    在后台获取吧
    前台不知道怎么获取.
     DropDownList ddl1 = gvr.FindControl("DropDownList1") as DropDownList;
      

  8.   

    以下是一个分页、排序、添加数据、修改数据、删除数据的完整例子,该例子为了演示各种应用效果,增加了图片上载功能,并使用部分代码指定数据源参数,也可以与其他条件联合使用,比如数据验证和计算等。
    C#:
    <%@ Page Language="C#" AutoEventWireup="true" Debug="true" %>
    <%@ Import Namespace="System.Data" %>
    <script runat="server">
    string GetUserPhoto(object pathPhoto)
    {
     if (pathPhoto == DBNull.Value)
     {
       return "<img src='../Images/none.gif'>";
     }
     else
     {
       return "<img src='../Upload/" + pathPhoto.ToString() + "'>";
     }
    }protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
     if (e.Row.RowType == DataControlRowType.DataRow)
     {
       if (e.Row.RowIndex == GridView1.EditIndex)
       {     DataRowView rowItem = (DataRowView)e.Row.DataItem;     DropDownList clsName = (DropDownList)e.Row.FindControl("uClassName");
         if (rowItem["ClassName"] != DBNull.Value)
         {
           clsName.Items.FindByText(rowItem["ClassName"].ToString()).Selected = true;
         }     if (rowItem["Gender"] != DBNull.Value)
         {       RadioButtonList oGender = (RadioButtonList)e.Row.FindControl("uGender");
           oGender.SelectedIndex = (Convert.ToBoolean(rowItem["Gender"]) ? 0 : 1);
         }
       }
     }
    }protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
     if (e.CommandName == "New")
     {
       string StudentTitle = ((TextBox)GridView1.FooterRow.FindControl("NewTitle")).Text;
       if (StudentTitle.Trim() == "")
       {
         ErrorMsg.Text = "请输入姓名";
         return;
       }
       string StudentBirthDay = ((TextBox)GridView1.FooterRow.FindControl("NewBirthDay")).Text;
       bool StudentGender = ((RadioButtonList)
         GridView1.FooterRow.FindControl("NewGender")).SelectedValue == "男" ? true : false;
       string StudentClassName = ((DropDownList)
         GridView1.FooterRow.FindControl("NewClassName")).SelectedValue;
       FileUpload oUpload = (FileUpload)GridView1.FooterRow.FindControl("AddPhoto");
       String FileName = "";
       FileName = Guid.NewGuid().ToString("D") + System.IO.Path.GetExtension(oUpload.FileName);
       oUpload.SaveAs(Server.MapPath("~") + "/Upload/" + FileName);
       string sql = "Insert Into Student (Title,BirthDay,Gender,PhotoPath,ClassName)";
       sql += " Values(@Title,@BirthDay,@Gender,@PhotoPath,@ClassName)";
       SqlDataSource1.InsertCommand = sql;
       SqlDataSource1.InsertParameters.Add("@Title", TypeCode.String, StudentTitle);
       SqlDataSource1.InsertParameters.Add("@BirthDay", TypeCode.DateTime, StudentBirthDay);
       SqlDataSource1.InsertParameters.Add("@Gender", TypeCode.Boolean, StudentGender.ToString());
       SqlDataSource1.InsertParameters.Add("@PhotoPath", TypeCode.String, FileName);
       SqlDataSource1.InsertParameters.Add("@ClassName", TypeCode.String, StudentClassName);
       SqlDataSource1.Insert();
     } if (e.CommandName == "Update")
     {
       string StudentTitle = ((TextBox)GridView1.Rows[GridView1.EditIndex].FindControl("uTitle")).Text;
       string StudentBirthDay = ((TextBox)
         GridView1.Rows[GridView1.EditIndex].FindControl("uBirthDay")).Text;
       bool StudentGender = ((RadioButtonList)
         GridView1.Rows[GridView1.EditIndex].FindControl("uGender")).SelectedValue == "男" ? true : false;
       string StudentClassName = ((DropDownList)
         GridView1.Rows[GridView1.EditIndex].FindControl("uClassName")).SelectedValue;
       string StudentID = GridView1.DataKeys[GridView1.EditIndex].Value.ToString();
       String FileName = "";
       string sql = "";
       String PhotoPath = "";
       bool HasFileUploaded = false;   FileUpload oUpload = (FileUpload)GridView1.Rows[GridView1.EditIndex].FindControl("uPhoto");
       if (oUpload.HasFile)
       {
         PhotoPath = Guid.NewGuid().ToString("D") + System.IO.Path.GetExtension(oUpload.FileName);
         oUpload.SaveAs(Server.MapPath("~") + "/Upload/" + PhotoPath);
         HasFileUploaded = true;
       }   if (HasFileUploaded)
       {
         sql = "Update Student Set Title=@Title,BirthDay = @BirthDay,";
         sql += "Gender=@Gender,PhotoPath=@PhotoPath,ClassName=@ClassName Where id=@id";
       }
       else
       {
         sql = "Update Student Set Title=@Title,BirthDay = @BirthDay," ;
         sql += "Gender=@Gender,ClassName=@ClassName Where id=@id";
       }
       SqlDataSource1.UpdateCommand = sql;
       SqlDataSource1.UpdateCommandType = SqlDataSourceCommandType.Text;   SqlDataSource1.UpdateParameters.Add("@Title", TypeCode.String, StudentTitle);
       SqlDataSource1.UpdateParameters.Add("@BirthDay", TypeCode.DateTime, StudentBirthDay);
       SqlDataSource1.UpdateParameters.Add("@Gender", TypeCode.Boolean, StudentGender.ToString());
       if (HasFileUploaded)
       {
         SqlDataSource1.UpdateParameters.Add("@PhotoPath", TypeCode.String, PhotoPath);
       }
       SqlDataSource1.UpdateParameters.Add("@ClassName", TypeCode.String, StudentClassName);
       SqlDataSource1.UpdateParameters.Add("@id", TypeCode.Int32, StudentID);   SqlDataSource1.Update();
     }
    }  
    </script>
      

  9.   


    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title>GridView 插入、删除、修改的例子</title>
    </head>
    <body>
    <form id="form1" runat="server">
     <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
       AllowPaging="true" AllowSorting="true" PageSize="5" DataSourceID="SqlDataSource1"
       OnRowDataBound="GridView1_RowDataBound" ShowFooter="true"
       OnRowCommand="GridView1_RowCommand">
       <Columns>
         <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True"
           Visible="false" SortExpression="id" />
         <asp:TemplateField HeaderText="姓名" SortExpression="Title">
           <ItemTemplate>
             <%#Eval("Title") %>
           </ItemTemplate>
           <EditItemTemplate>
             <asp:TextBox ID="uTitle" runat="server" Text='<%#Eval("Title") %>'></asp:TextBox>
           </EditItemTemplate>
           <FooterTemplate>
             <asp:TextBox ID="NewTitle" runat="server"></asp:TextBox>
           </FooterTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderText="生日" SortExpression="BirthDay">
           <ItemTemplate>
             <%#Eval("BirthDay", "{0:yyyy年M月d日}")%>
           </ItemTemplate>
           <EditItemTemplate>
             <asp:TextBox ID="uBirthDay" runat="server" Text='<%#Eval("BirthDay", "{0:yyyy-M-d}")%> '/>
           </EditItemTemplate>
           <FooterTemplate>
             <asp:TextBox ID="NewBirthDay" runat="server"></asp:TextBox>
           </FooterTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderText="性别" SortExpression="Gender">
           <ItemTemplate>
             <%#(Eval("Gender")).ToString() =="True"?"男":"女"%>
           </ItemTemplate>
           <EditItemTemplate>
             <asp:Label ID="g" Text='<%#(Eval("Gender")).ToString() =="True"?"男":"女"%>'
               Visible="false" runat="server"></asp:Label>
             <asp:RadioButtonList ID="uGender" runat="server">
               <asp:ListItem Text="男"></asp:ListItem>
               <asp:ListItem Text="女"></asp:ListItem>
             </asp:RadioButtonList>
           </EditItemTemplate>
           <FooterTemplate>
             <asp:RadioButtonList ID="NewGender" runat="server">
               <asp:ListItem Selected="true" Text="男"></asp:ListItem>
               <asp:ListItem Text="女"></asp:ListItem>
             </asp:RadioButtonList>
           </FooterTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderText="年级">
           <ItemTemplate>
             <%#Eval("ClassName")%>
           </ItemTemplate>
           <EditItemTemplate>
             <asp:DropDownList ID="uClassName" runat="server">
               <asp:ListItem Text="小学" Value="小学"></asp:ListItem>
               <asp:ListItem Text="中学" Value="中学"></asp:ListItem>
               <asp:ListItem Text="高中" Value="高中"></asp:ListItem>
               <asp:ListItem Text="大学" Value="大学"></asp:ListItem>
             </asp:DropDownList>
           </EditItemTemplate>
           <FooterTemplate>
             <asp:DropDownList ID="NewClassName" runat="server">
               <asp:ListItem Text="小学" Value="小学"></asp:ListItem>
               <asp:ListItem Text="中学" Value="中学"></asp:ListItem>
               <asp:ListItem Text="高中" Value="高中"></asp:ListItem>
               <asp:ListItem Text="大学" Value="大学"></asp:ListItem>
             </asp:DropDownList>
           </FooterTemplate>
         </asp:TemplateField>
         <asp:TemplateField>
           <ItemTemplate>
             <%# GetUserPhoto(Eval("PhotoPath")) %>
           </ItemTemplate>
           <EditItemTemplate>
             <asp:FileUpload ID="uPhoto" runat="server" />
           </EditItemTemplate>
           <FooterTemplate>
             <asp:FileUpload ID="AddPhoto" runat="server" />
           </FooterTemplate>
         </asp:TemplateField>
         <asp:CommandField ButtonType="Button" ShowCancelButton="true" ShowDeleteButton="true"
           ShowEditButton="true" CancelText="取消" DeleteText="删除" UpdateText="更新" 
           EditText="修改" HeaderText="操作" InsertVisible="false" 
           ShowInsertButton="true" NewText="添加学生" />
       </Columns>
     </asp:GridView>
     <asp:SqlDataSource ID="SqlDataSource1" runat="server" ProviderName="System.Data.OleDb"
       ConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\ASPNET20Book.mdb;"
       SelectCommand="SELECT * FROM [Student] ORDER BY [id] DESC" DataSourceMode="DataSet"
       DeleteCommand="Delete from Student Where id=@id">
       <DeleteParameters>
         <asp:Parameter Name="id" Type="Int32" />
       </DeleteParameters>
     </asp:SqlDataSource>
     <asp:Label ID="ErrorMsg" runat="server" ForeColor="red"></asp:Label>
    </form>
    </body>
    </html>
      

  10.   

    更改前台ASPX文件中的EditItemTemplate
    -----------------------------------------
    <EditItemTemplate>
    <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="..." DataTextField="..." DataValueField="..." SelectedValue='<%# Bind("绑定的字段名") %>'/>                        
    </EditItemTemplate>
      

  11.   

    写个返回string(参数DropDownList选择的值)的方法
      接受参数 就是调用方法
      

  12.   

    to 丁一。bind要和gridview同一张表才行。。问题是不是同一张表。
      

  13.   

    to  孟子大侠。其实所有的问题合起来就一个问题。在sqldatasource中就有updatequery这项。点开就有自己写的SQL的update的语句。中间where id=@id1,id1就是参数。有个参数源。选择control。然后就是controlid不知道怎么写。这个controlid要写的内容就是gridview编辑模板(<edititemtemplate>中的dropdownlist。如果只有一张表。那按丁一的方法就可以了。不用这么麻烦,现在是多张表。dropdownlist中的和gridview的数据源不同。
      

  14.   

    GridView1.TemplateControl.FindControl("DropDownList1").ToString()
    ====================================================
    若在RowDataBound事件中
    则((dropdownlist)GridView1.e.Row.FindControl("DropDownList1")).SelectValue.tostring()
      

  15.   

    。就是有两张表。一张是用户ID和用户权限代码。另一张是权限代码和权限名字。。这样。我用select时就取出用户ID和用户权限名字。用gridview就可以很容易显示。我在edititemtemplate加了dropdownlist控件。这样点编辑时就会出现下拉框,而这个下拉框的内容仅仅是第二张表的权限名字。更改后希望能把权限代码存进第一张表里。而datasource有个带参数的update而且可以绑定到控件上,问题是外面的控件都能绑。就是这个gridview里的dropdownlist他没法绑定。controlid啊。。怎么写啊。想想有可能只有点击gridview的编辑后才能得到dropdownlist。现在就是不知道怎么写了。
      

  16.   

    不知道我的理解对不对,你是想通过选择DropDownList的选择来改变用户的权限?..
      

  17.   

    得到点后的值,你想做什么呢,不就是想做数据修改时,可以实现直接下拉列表不需要手动输入吗?这样的话直接给DROPDOWNLIST BIND一个数据源不就成了。
      

  18.   

    to 丁一。没错。。就仅仅这样而已可是似乎想仅仅从controlid这里实现不了的样子。
    to gcaling2006。给dropdownlist绑定什么数据源。。点击的值是从另一张表里取出来的。。但是保存到另外一张表。
      

  19.   

    自己总结:几天了自己搞定。controlid只能是页面上的controlid,这点可能有点片面但是在线MSDN上写的就是页面上的而没说所有的控件。那就只能退而求其次。
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            ControlParameter cp_roleid =
               new ControlParameter("role_id", TypeCode.String, GridView1.Rows[GridView1.EditIndex].FindControl("DropDownList1").UniqueID.ToString(), "SelectedValue");
            SqlDataSource1.UpdateParameters.Add(cp_roleid);}
    这个role_id就是SQL里的参数。而GridView1.Rows[GridView1.EditIndex].FindControl("DropDownList1").本来是直接点tostring后来发现不行。又突然发现这个uniqueid。一试居然通过,回想刚开始时如果有这个uniqueid不就直接可以写入controlid,行不行不知道,估计不行。因为dropdownlist是在编辑状态下才生成的,这个uniqueid应该也是在编辑时才生成的。这个方法应该也是最快的方法了,其实自己取得值。再保存是可以,只是我嫌速度慢。OK。好想结贴。可它总是没法结贴。到底是我的问题还是CSDN的问题。同时感谢上面各位大大们的意见,谢了。
      

  20.   

    在编辑时取所选行的索引,然后根据rows.cell[index].constrol[第几个单元格]就OK了