Finding drop down list control from a stored procedure in edit item template of gridview in asp.net c#

StackOverflow https://stackoverflow.com/questions/16900413

Вопрос

I am trying to find a DropDownList control on the EditItemTemplate of a grid view, to populate it with results from a query before it is drawn, but the control is never found.

ddlParent == null

Always!

I may be missing something very obvious but i have tried about 8 different methods to get this find control working, but no matter what i do, it comes up null.

I have included both the ASP and the C#, the sql should not be important as i cant even reach the call!

ASP:

            <asp:TemplateField SortExpression="LocationArea2.Name" HeaderText="Parent Location Area">
                <ItemTemplate>
                    <asp:Label runat="server" Text='<%# Eval("LocationArea2.Name") %>' />
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:DropDownList ID="ddlParent" runat="server" AppendDataBoundItems="true" DataTextField="LocationArea2.Name"
                        DataValueField="ParentID" AutoPostBack="false" SelectedValue='<%# Bind("ParentID") %>'>
                    </asp:DropDownList>
                </EditItemTemplate>
            </asp:TemplateField>

C#:

protected void gvLocationArea_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (gvLocationArea.EditIndex == e.Row.RowIndex)
        {
            DropDownList ddlParent = (DropDownList)gvLocationArea.Rows[gvLocationArea.EditIndex].FindControl("ddlParent");
            if (ddlParent != null)
            {
                using (SalesSQLEntities db = new SalesSQLEntities())
                {
                    ddlParent.DataSource = db.GetRecursiveAreaList(Convert.ToInt32(((TextBox)gvLocationArea.Rows[gvLocationArea.EditIndex].FindControl("txtLocationAreaID")).Text), true);
                    ddlParent.DataBind();
                    ddlParent.Items.Add(new ListItem("* None", ""));
                }
            }
        }
    }

I know there is something missing here, the control is just never found no matter what i've tried!

Это было полезно?

Решение

Instead of doing a FindControl, use an offset index of the column in question and get the first control:

(DropDownList)gvLocationArea.Rows[gvLocationArea.EditIndex].Cells[INDEX OF THE DDL].Controls[0]
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top