10

我在表单上有一个 gridview 并有一些模板字段,其中之一是:

<asp:TemplateField HeaderText="Country" HeaderStyle-HorizontalAlign="Left">
    <EditItemTemplate>
        <asp:DropDownList ID="DdlCountry" runat="server" DataTextField="Country" DataValueField="Sno">
        </asp:DropDownList>
    </EditItemTemplate>
    </asp:TemplateField>

现在在 RowEditing 事件中,我需要获取国家下拉列表的选定值,然后我将该值设置为 Ddlcountry.selectedvalue=value; 这样当编辑项模板的下拉列表出现时,它将显示所选值而不是下拉列表的 0 索引。但我无法获得下拉列表的值。我已经尝试过了:

int index = e.NewEditIndex;
DropDownList DdlCountry = GridView1.Rows[index].FindControl("DdlCountry") as DropDownList;

需要帮助。谢谢。

4

2 回答 2

17

您需要GridView再次绑定数据才能访问EditItemTemplate. 所以试试这个:

int index = e.NewEditIndex;
DataBindGridView();  // this is a method which assigns the DataSource and calls GridView1.DataBind()
DropDownList DdlCountry = GridView1.Rows[index].FindControl("DdlCountry") as DropDownList;

但相反我会使用RowDataBound这个,否则你正在复制代码:

protected void gridView1_RowDataBound(object sender, GridViewEditEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.DataRow)
  {
        if ((e.Row.RowState & DataControlRowState.Edit) > 0)
        {
          DropDownList DdlCountry = (DropDownList)e.Row.FindControl("DdlCountry");
          // bind DropDown manually
          DdlCountry.DataSource = GetCountryDataSource();
          DdlCountry.DataTextField = "country_name";
          DdlCountry.DataValueField = "country_id";
          DdlCountry.DataBind();

          DataRowView dr = e.Row.DataItem as DataRowView;
          Ddlcountry.SelectedValue = value; // you can use e.Row.DataItem to get the value
        }
   }
}
于 2013-01-29T13:40:08.520 回答
7

您可以尝试使用此代码 - 基于EditIndex property

var DdlCountry  = GridView1.Rows[GridView1.EditIndex].FindControl("DdlCountry") as DropDownList;

链接:http: //msdn.microsoft.com/fr-fr/library/system.web.ui.webcontrols.gridview.editindex.aspx

于 2013-01-29T13:40:55.410 回答