Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
89 views
in Technique[技术] by (71.8m points)

c# - how to find control in edit item template?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
        }
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...