i have a gridview on the form and have some template field, one of them is:
<asp:TemplateField HeaderText="Country" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:DropDownList ID="DdlCountry" runat="server" DataTextField="Country" DataValueField="Sno">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
now on the RowEditing event i need to get the selected value of dropdownlist of country and then i will set that value as Ddlcountry.selectedvalue=value; so that when dropdownlist of edit item template appears it will show the selected value not the 0 index of dropdownlist. but i am unable to get the value of dropdown list. i have tried this already:
int index = e.NewEditIndex;
DropDownList DdlCountry = GridView1.Rows[index].FindControl("DdlCountry") as DropDownList;
need help please. thanx.
You need to databind the GridView
again to be able to access the control in the EditItemTemplate
. So try this:
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 RowDataBound
for this, otherwise you're duplicating 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
}
}
}
You can try wit this code - based on 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With