none
looping through the gridview rows and columns

    Question

  • hi all

            i have a grid view with 4 columns , in which first column is a bound field , which has the names of some roles , and other 3 columns consists of

    Chechboxes ( just like giving the permission ) ,

    now my need is i have to iterate through the grid's roles and columns and check which checkbox has been checked and for which row (roles) and update the same in DB .

    how can i perform this iteration.

    waiting for the replies , thanks in advance

    Monday, December 10, 2012 8:52 AM

Answers

All replies

  • Use the RowDataBound event that is fired for each row in you Gridview when you bind the data to it.Use the GridView.Columns property for accessing the column info, and the GridView.Rows properties for loop the rows in the grideview.

    Roar Jørstad aka sveroa
    Senior Consultant, EVRY as
    Blog: Notebook, trick & tips
    Please mark as answer or helpful if my post is useful

    • Proposed as answer by sobha1 Monday, March 04, 2013 6:38 PM
    Monday, December 10, 2012 9:04 AM
  • Here is a code example for the RowDataBound event:

    protected void Users_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        BOScheme scheme = new BOScheme();
        string onmouseoverStyle = "this.style.backgroundColor='darkseagreen';style.cursor='hand'";
        string onmouseoutStyle = "this.style.backgroundColor='#@BackColor'";
        string rowBackColor = String.Empty;
        bool isGridEmpty = Convert.ToBoolean(ViewState["emptyGrid"]);
        if (e.Row.RowType == DataControlRowType.DataRow && isGridEmpty == false)
        {
            Label RoleLabel = (Label)e.Row.FindControl("RoleLabel");
            CheckBox chkSelected = (CheckBox)e.Row.FindControl("chkSelected");
            int schemeId = Convert.ToInt32(Request.QueryString["schemeID"]);
            int userId = Convert.ToInt32(((DataRowView)e.Row.DataItem)["id_num"]);
            chkSelected.Checked = scheme.isMember(schemeId, userId);
            userRole role = (userRole)(((DataRowView)e.Row.DataItem)["role_num"]);
            RoleLabel.Text = role.ToString();
            if (e.Row.RowState == DataControlRowState.Alternate)
            {
                rowBackColor = System.Drawing.ColorTranslator.ToHtml(Users.AlternatingRowStyle.BackColor).ToString();
            }
            else
            {
                rowBackColor = System.Drawing.ColorTranslator.ToHtml(Users.RowStyle.BackColor).ToString();
            }
            e.Row.Attributes.Add("onmouseover", onmouseoverStyle);
            e.Row.Attributes.Add("onmouseout", onmouseoutStyle.Replace("#@BackColor", rowBackColor));
            e.Row.Attributes.Add("onclick", "document.getElementById('" + chkSelected.ClientID + "').click();");
        }
        if (e.Row.RowType == DataControlRowType.Header)
        {
            int sortColumnIndex = GetSortColumnIndex();
            if (sortColumnIndex != -1)
            {
                AddSortImage(sortColumnIndex, e.Row);
            }
        }
    }


    Roar Jørstad aka sveroa
    Senior Consultant, EVRY as
    Blog: Notebook, trick & tips
    Please mark as answer or helpful if my post is useful

    Monday, December 10, 2012 9:10 AM
  • Hi sevroa,

              Thanks for the reply ,

    But i need this functionality to happen when i click on a button

    Tuesday, December 11, 2012 7:22 AM
  • Hi sevroa,

              Thanks for the reply ,

    But i need this functionality to happen when i click on a button

    You can still use the Columns and Rows properties.

    Markup:

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:BoundField DataField="Id" HeaderText="Id" />
            <asp:BoundField DataField="Name" HeaderText="Name" />
            <asp:CheckBoxField DataField="Access" Text="Access?" />
        </Columns>
    </asp:GridView>
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

    Code-behind:

    protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.DataSource = new List<Myclass>() { 
                new Myclass(1, "aaa", true), 
                new Myclass(2, "bbb", false), 
                new Myclass(3, "ccc", false) 
        };
        GridView1.DataBind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow s in GridView1.Rows)
        {
        }
    }


    Roar Jørstad aka sveroa
    Senior Consultant, EVRY as
    Blog: Notebook, trick & tips
    Please mark as answer or helpful if my post is useful

    Tuesday, December 11, 2012 8:32 AM
  • protected void bt_save_Click(object sender, EventArgs

    e)

    string getId = ("select ScreenId from dbo.Tbl_Mst_Screens where ScreenName='" + SList.SelectedItem.Value + "' ");

    conn.Open();

    SqlCommand cmd1 = new SqlCommand(getId, conn);

    int i = Convert.ToInt32(cmd1.ExecuteScalar());

    conn.Close();

    foreach (GridViewRow row in grid_role.Rows)

    {

    for( int count=0 ; count < grid_role.Rows.Count ; count++)

    {

    string roleName = grid_role.Rows[count].Cells[count].Text;

    if (((System.Web.UI.WebControls.CheckBox)row.FindControl("chkViewStatus")).Checked)

    {

    string query = @"Update MenuRoleRights set ViewRight = 1

    From MenuRoleRights

    INNER JOIN Screens

    ON MenuRoleRights.ScreenId= Screens.ScreenId

    INNER JOIN Role

    ON MenuRoleRights.RoleId=Role.RM_RoleID

    WHERE Screens.ScreenId= "

    + i + " AND RM_RoleName = ' +roleName+'";

    SqlCommand View = new SqlCommand(query, conn);

    try

    {

    conn.Open();

    View.ExecuteNonQuery();

    conn.Close();

    }

    catch (Exception ex)

    {

    MessageBox.Show(ex.Message);

    }

    }

    else

    {

    string query = @"Update MenuRoleRights set ViewRight = 0

    From MenuRoleRights

    INNER JOIN Screens

    ON MenuRoleRights.ScreenId= Screens.ScreenId

    INNER JOIN Role

    ON MenuRoleRights.RoleId=Role.RM_RoleID

    WHERE Screens.ScreenId= "

    + i + " AND RM_RoleName = '+ roleName +'" ;

    SqlCommand View = new SqlCommand(query, conn);

    try

    {

    conn.Open();

    View.ExecuteNonQuery();

    conn.Close();

    }

    catch (Exception ex)

    {

    MessageBox.Show(ex.Message);

    }

    }

    if (((System.Web.UI.WebControls.CheckBox)grid_role.Rows[count].FindControl("chkAddStatus")).Checked)

    {

    string query = @"Update MenuRoleRights set AddRight = 1

    From MenuRoleRights

    INNER JOIN Screens

    ON MenuRoleRights.ScreenId= Screens.ScreenId

    INNER JOIN Role

    ON MenuRoleRights.RoleId=Role.RM_RoleID

    WHERE ScreenId= "

    + i + " AND RM_RoleName = ' + roleName + '";

    SqlCommand Add = new SqlCommand(query, conn);

    try

    {

    conn.Open();

    Add.ExecuteNonQuery();

    conn.Dispose();

    }

    catch (Exception ex)

    {

    MessageBox.Show(ex.Message);

    }

    }

    else

    {

    string query = @"Update MenuRoleRights set AddRight = 0

    From MenuRoleRights

    INNER JOIN Screens

    ON MenuRoleRights.ScreenId= Screens.ScreenId

    INNER JOIN Role

    ON MenuRoleRights.RoleId=Role.RM_RoleID

    WHERE Screens.ScreenId= "

    + i + " AND Role.RM_RoleName = ' + roleName + '";

    SqlCommand Add = new SqlCommand(query, conn);

    try

    {

    conn.Open();

    Add.ExecuteNonQuery();

    conn.Close();

    }

    catch (Exception ex)

    {

    MessageBox.Show(ex.Message);

    }

    }

    if (((System.Web.UI.WebControls.CheckBox)grid_role.Rows[count].FindControl("chkEditStatus")).Checked)

    {

    string query = @"Update MenuRoleRights set EditRight = 1

    From MenuRoleRights

    INNER JOIN Screens

    ON MenuRoleRights.ScreenId= Screens.ScreenId

    INNER JOIN Role

    ON MenuRoleRights.RoleId=Role.RM_RoleID

    WHERE Screens.ScreenId= "

    + i + " AND Role.RM_RoleName = ' + roleName + '";

    SqlCommand Edit = new SqlCommand(query, conn);

    try

    {

    conn.Open();

    Edit.ExecuteNonQuery();

    conn.Close();

    }

    catch (Exception ex)

    {

    MessageBox.Show(ex.Message);

    conn.Dispose();

    }

    }

    else

    {

    string query = @"Update MenuRoleRights set EditRight = 0

    From MenuRoleRights

    INNER JOIN Screens

    ON MenuRoleRights.ScreenId=Screens.ScreenId

    INNER JOIN Role

    ON MenuRoleRights.RoleId=Role.RM_RoleID

    WHERE Screens.ScreenId= "

    + i + " AND Role.RM_RoleName = ' + roleName + '";

    SqlCommand Edit = new SqlCommand(query, conn);

    try

    {

    conn.Open();

    Edit.ExecuteNonQuery();

    conn.Close();

    }

    catch (Exception ex)

    {

    MessageBox.Show(ex.Message);

    }

    }

    }

    }

    } this is the what i have written , what am i doin wrong

    Tuesday, December 11, 2012 11:11 AM
  • on what line? error message? or just doesn't code what you expect?

    Please post a more readable code with identition and single line space.


    Roar Jørstad aka sveroa
    Senior Consultant, EVRY as
    Blog: Notebook, trick & tips
    Please mark as answer or helpful if my post is useful

    Tuesday, December 11, 2012 3:47 PM
  • protected void bt_save_Click(object sender, EventArgs e)
    {
     foreach (GridViewRow row in grid_role.Rows)
     {
      for( int count=0 ; count < grid_role.Rows.Count ; count++)
      {
       string roleName = grid_role.Rows[count].Cells[count].Text;
       if (((System.Web.UI.WebControls.CheckBox)row.FindControl ("chkViewStatus")).Checked)
       {
     
       }
       if (((System.Web.UI.WebControls.CheckBox)row.FindControl ("chkEditStatus")).Checked)
       {
     
       }
       if (((System.Web.UI.WebControls.CheckBox)row.FindControl ("chkViewStatus")).Checked)
       {
     
       }
      }
     }
    }
    am getiing a exception on the line string roleName = grid_role.Rows[count].Cells[count].Text; for the 2nd iteration ,
    first iteration is working fine , but on 2nd iteration either its giving an exception or is not taking
    any value from the gridview column
    Wednesday, December 12, 2012 6:16 AM
  • and also i want to know , is there any other way to perform this .
    Wednesday, December 12, 2012 6:18 AM
  • That line should look like this:

    string roleName = grid_role.Rows[count].Cells[0].Text; 
    string col2 = grid_role.Rows[count].Cells[1].Text; 
    string col3 = grid_role.Rows[count].Cells[2].Text; 
    where the 'count' loop variable indicated which row, and the 'Cells[n]' indicates the fixed rows you are going to check. The first column might not be the role, but this is just an example. I have put 2 more columns - col2 and col3 - to illustrate this.

    Roar Jørstad aka sveroa
    Senior Consultant, EVRY as
    Blog: Notebook, trick & tips
    Please mark as answer or helpful if my post is useful

    Wednesday, December 12, 2012 7:16 AM
  • thanks for reply sveroa , but can u plz be more specific , i dint understand , am new to all this , i thought of using string roleName = grid_role.Rows[count].Cells[count].Text; will it do me any good , if not , can u post some code snippets
    Wednesday, December 12, 2012 9:07 AM
  • This will give you a good answer and example on how to traverse the rows and columns

    http://stackoverflow.com/questions/2023187/loop-through-all-rows-and-columns-of-a-gridview-using-c-sharp

    Roar Jørstad aka sveroa
    Senior Consultant, EVRY as
    Blog: Notebook, trick & tips
    Please mark as answer or helpful if my post is useful

    Wednesday, December 12, 2012 1:00 PM
  • You may want to give a stare to this code sample, you may freely download it from : http://sdrv.ms/VOkLPA


    Aarsh Talati

    Wednesday, December 12, 2012 5:38 PM
  • Hi sevroa ,

          The example that link consists of, contains , just how to loop through gridview rows and columns , but my main concern is , i have to also get that roleName from the gridView into a string so that the query what i have written to update the table for all the checkbox checked works fine too.

    Thursday, December 13, 2012 9:44 AM
  • You have to use the FindControl method on the row/cell to find the control you are looking for. The return Control class needs to be casted to the desired control (CheckBox???) where you store your access value. Then, you can use the Checked property to see of the current row is checked or not. This have to be done for all the rows as I can see now.

    Roar Jørstad aka sveroa
    Senior Consultant, EVRY as
    Blog: Notebook, trick & tips
    Please mark as answer or helpful if my post is useful

    Thursday, December 13, 2012 10:54 AM
  • I've a demo application for that, which actually catches up which row has been clicked : http://sdrv.ms/VOkLPA also "rowcommnad" event is useful for you, as you may do e.selectedRowIndex or something like that to retrieve the index of selected row or may use DataKeys (Demonstrated in this example) to directly get the Key (CustomerID of Northwind DB in my case) of the row selected and can find the record from your datatable, like I've done.

    Aarsh Talati

    Thursday, December 13, 2012 3:47 PM
  • hi Aarsh ,

            can post the example code in this blog , i cannot access the links which u have given

    Friday, December 14, 2012 5:33 AM
  • Hi v k b,

    For ASP.NET issue you can use below bore appropriate forum:

    http://forums.asp.net

    Thanks


    Bob Shen
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Friday, December 21, 2012 3:54 AM
    Moderator