gridView RowEditing .

Feb 18 2013 9:10 AM
I am trying populate a gridview with a datasource when it is in Edit mode.

This is what I am tryiing but learnt that you cannot use this in the edit event.

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

  if (grd_User.EditIndex != -1)
  {
  DropDownList ddl = grd_User.Rows[grd_User.EditIndex].FindControl("drp_Val_ServiceArea") as DropDownList;

  if (ddl != null)
  {
  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
  };

  ddl.DataTextField = "ServiceArea";
  ddl.DataValueField = "ServiceAreaId";
  ddl.DataSource = result;
  ddl.DataBind();
  }
  }
  }
  // Reload Grid
  // ===========
  LoadGrid();
  }

When I get to if (ddl != null)
it just jumps the the end and LoadGrid()

but what I have been pointed to is this.

  protected void grd_User_PreRender(object sender, EventArgs e)
  {
  if (grd_User.EditIndex != -1)
  {
  DropDownList ddl = grd_User.Rows[grd_User.EditIndex].FindControl("drp_Val_ServiceArea") as DropDownList;

  if (ddl != null)
  {
  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
  };

  ddl.DataTextField = "ServiceArea";
  ddl.DataValueField = "ServiceAreaId";
  ddl.DataSource = result;
  ddl.DataBind();
  }
  }
  }
  }
but dont now how to implement this when the RowEditing event is fired.

This is my Grid template for the EditItemTemplate
  <EditItemTemplate>
  <asp:DropDownList ID="drp_Val_ServiceArea" runat="server" AutoPostBack="True">
  </asp:DropDownList>
  </EditItemTemplate>
  <ItemTemplate>
  <asp:Label ID="lbl_Bind_ServiceArea" runat="server" Text='<%# Bind("ServiceArea") %>'></asp:Label>
  </ItemTemplate>


 That is the Answer.

   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();
  }

  }
  }
  }