Sunday, February 14, 2016

Editable Grid View (Part 2)

          Click here to view Part1
  • Within Grid View RowDataBound method, we can bind the drop down lists in Edit item template.
[code] protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { try { if (e.Row.RowType == DataControlRowType.DataRow && GridView1.EditIndex == e.Row.RowIndex) { DropDownList ddlLocation = (DropDownList)e.Row.FindControl("ddlLocation"); DataTable dtLocation = myService.getLocation(); ddlLocation.DataSource = dtLocation; ddlLocation.DataValueField = "ListId"; ddlLocation.DataTextField = "LocationName"; ddlLocation.DataBind(); Label lblLocationId = (Label)e.Row.FindControl("lblLocationId"); ddlLocation.SelectedValue = lblLocationId.Text; } } catch (Exception ex) { throw ex; } } [/code]
  • Add following codes within RowEditing and on RowCancellingEdit methods.
[code] protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { try { GridView1.EditIndex = e.NewEditIndex; bindDataToGrid(); } catch (Exception ex) { throw ex; } } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { try { GridView1.EditIndex = -1; bindDataToGrid(); } catch (Exception ex) { throw ex; } } } [/code]


  • Write the code as follows for row updating.
[code] protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { try { TextBox txtAddress = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtAddress"); DropDownList ddlLocation = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlLocation"); CheckBox chkEditActive = (CheckBox)GridView1.Rows[e.RowIndex].FindControl("chkEditActive"); string custListId = GridView1.DataKeys[e.RowIndex].Value.ToString(); string address = txtAddress.Text; string locationListId = string.Empty; bool isActive = false; if (chkEditActive.Checked) { isActive = true; } if(ddlLocation.SelectedIndex > 0) { locationListId = ddlLocation.SelectedValue; } bool status = myService.updateCustomer(locationListId, address, isActive, custListId); GridView1.EditIndex = -1; bindDataToGrid(); } catch (Exception ex) { throw ex; } } [/code]
  • Grid view design

[code] [/code]

No comments:

Post a Comment