在已绑定的gridview中绑定ddl

时间:2013-02-18 10:31:08

标签: c# asp.net .net gridview

我试图在搜索框返回结果时绑定ddl。 DDL的约束如下:

<asp:TemplateField HeaderText="Service Area" SortExpression="ServiceArea">
  <EditItemTemplate>
    <asp:DropDownList ID="drp_Val_ServiceArea" runat="server" DataTextField="ServiceArea"
        DataValueField='<%# Eval("ServiceAreaId") %>'>
    </asp:DropDownList>
  </EditItemTemplate>
  <ItemTemplate>
    <asp:Label ID="lbl_Bind_ServiceArea" runat="server" Text='<%# Bind("ServiceArea") %>'></asp:Label>
  </ItemTemplate>
</asp:TemplateField>

当我使用搜索并加载网格时,页面加载正常。 当我按下编辑按钮时,异常是对象未设置为实例。 和ddl.DataTextField = "ServiceArea"上的错误。

protected void grd_User_RowEditing(object sender, GridViewEditEventArgs e)
{
grd_User.EditIndex = e.NewEditIndex;


using (var _db = new dbDataContext())
{
    var result = from s in _db.tbl_ServiceAreas
                    where s.Deleted == false
                    select new
                    {
                        s.ServiceAreaId,
                        s.ServiceArea
                    };

    if ((DataControlRowState.Edit) > 0)
    {

        DropDownList ddl = (DropDownList)grd_User.Rows[e.NewEditIndex].Cells[0].FindControl("drp_Val_ServiceArea");

        ddl.DataTextField = "ServiceArea";
        ddl.DataValueField = "ServiceAreaId";
        ddl.DataSource = result;
        ddl.DataBind();

    }
}
 LoadGrid();
}

这是因为网格已绑定到ServiceArea吗?

以下是我一直在寻找的答案。

        protected void grd_User_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowState == DataControlRowState.Edit)
        {
            DropDownList ddl = (DropDownList)e.Row.FindControl("drp_Val_ServiceArea");

            using (var _db = new dbDataContext())
            {
                var result = from s in _db.tbl_Users
                             where s.Deleted == false
                             select new
                             {
                                 s.ServiceAreaId,
                                 s.tbl_ServiceArea.ServiceArea
                             };

                foreach (var item in result)
                {
                    ddl.DataTextField = item.ServiceArea;
                    ddl.DataValueField = item.ServiceAreaId.ToString();
                    ddl.DataSource = result;
                    ddl.DataBind();
                }

            }
        }
    }

0 个答案:

没有答案