How to find a control in an element editing template?

i has the form of a grid in the form and has some template field, one of which:

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

Now in the RowEditing event I need to get the selected dropdownlist value of the country, and then I will set this value as Ddlcountry.selectedvalue = value; so when the drop-down list of the template for the edit item appears, it will show the selected value, not index 0 from the drop-down list. but I can not get the value of the dropdown list. I have already tried this:

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

need help please. Thanx.

+8
c # gridview
source share
2 answers

You need to bind to the GridView again in order to access the control in the EditItemTemplate . So try the following:

 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; 

But instead, I would use a RowDataBound for this, otherwise you are duplicating the code:

 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 } } } 
+15
source share

You can try using this code based on the EditIndex property

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

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

+5
source share

All Articles