Refactor Code

  • Gravatar
    Get Checked Values from GridView Using Extension Methods

    by azamsharp on 6/6/2008 8:17:02 PM
  • I was in a situation where I needed to get the checked rows out of the GridView control. So, this time I thought why not use extension methods to perform this task. So, I came up with the following methods.
  • public static class ExtensionMethods
    {
    public static GridViewRow[] GetCheckedRows(this GridView gv, string checkBoxId)
    {
    List<GridViewRow> checkedRows = new List<GridViewRow>();

    foreach (GridViewRow row in gv.Rows)
    {
    CheckBox chk = row.FindControl(checkBoxId) as CheckBox;
    if (chk == null) throw new Exception(String.Format("CheckBox ID {0} not found!",checkBoxId));

    if (chk.Checked)
    checkedRows.Add(row);
    }

    return checkedRows.ToArray<GridViewRow>();
    }
  • Refactor it!
Please log in to refactor the code! Login