0

I need to set these GridViews for updating by the admin. So since I have a lot of employees and a lot of courses in each GridView, I think the best way to update the GridView is to show the blank fields as checkboxes and when the Admin wants to update the record of one of the employees, all what he needs to do is just checking the checkboxes and click update button. I could be able to show the empty fields as checkboxes but now I don't know how to post the value of checking the checkbox to the database.

The scenario that I am looking for it is to make the system check every checkbox in each GridView, if it is already checked before, leave it as it is. If it was empty and it is just checked now, it should be added to the database in the record of the employee. Therefore, the GridView will be updated with clicking the save button. My original code is:

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
            <ItemTemplate>

                <asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("GroupID")%>' />

                <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                                    ConnectionString="<%$ ConnectionStrings:testConnectionString %>" 
                                    SelectCommandType="StoredProcedure" SelectCommand="kbiReport">
                                    <%--FilterExpression="[Division] like '{0}%' and [Organization] like '{1}%'">--%>

                    <%--<FilterParameters>
                        <asp:ControlParameter ControlID="ddlDivision" Name="Division" 
                                                 PropertyName="SelectedValue" Type="String" />
                        <asp:ControlParameter ControlID="ddlOrganization" Name="Organization" 
                                                PropertyName="SelectedValue" Type="String" />
                    </FilterParameters>--%>

                    <SelectParameters>
                        <%--ControlParameter is linked to the HiddenField above to generate different GridView based on different values 
                            of GroupID--%>
                        <asp:ControlParameter ControlID="HiddenField1" Name="GroupID" PropertyName="Value" />
                    </SelectParameters>
                </asp:SqlDataSource>

                <asp:GridView ID="GridView1" runat="server" 
                                AllowSorting="True" 
                                CellPadding="3" 
                                DataSourceID="SqlDataSource1" 
                                CssClass="mGrid"
                                AlternatingRowStyle-CssClass="alt" 
                                RowStyle-HorizontalAlign="Center" 
                                OnRowDataBound="GridView1_RowDataBound" OnDataBound="GridView1_DataBound">
                    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                    <HeaderStyle Font-Bold = "true" ForeColor="Black"/> 
                    <Columns>
                        <asp:CommandField ShowSelectButton="True" />

                        <%--<asp:TemplateField HeaderText="Select">
                        <ItemTemplate>
                        <asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="true" OnCheckedChanged="chkSelect_CheckedChanged"/>
                        </ItemTemplate>
                        </asp:TemplateField>--%>
                    </Columns>
                    <EditRowStyle BackColor="#999999" />
                    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                    <SortedAscendingCellStyle BackColor="#E9E7E2" />
                    <SortedAscendingHeaderStyle BackColor="#506C8C" />
                    <SortedDescendingCellStyle BackColor="#FFFDF8" />
                    <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                </asp:GridView>

            </ItemTemplate>
        </asp:Repeater>

        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                           ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
                           SelectCommand="SELECT DISTINCT GroupID FROM courses">
        </asp:SqlDataSource>

        <asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" />
        <br /><br />

The Code-Behind:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            foreach (TableCell c in e.Row.Cells)
            {
                // Check if the cell vlaue = Yes
                // if it is Yes, the cell will be colored with Light Green 
                if (c.Text.Equals("Yes"))
                {
                    c.BackColor = System.Drawing.Color.LightGreen;
                }
            }    
        }

        // The following is for changing the color of headers in each GridView based on the value of the HiddenFild 
        // BTW, the value of the HiddenField is the value of the GroupID in Group Table in the Database 
        else if(e.Row.RowType == DataControlRowType.Header){
            switch (((HiddenField)((GridView)sender).Parent.FindControl("HiddenField1")).Value)
            {
                case "1":
                    for (int i = 5; i &lt; e.Row.Cells.Count; i++)
                        e.Row.Cells[i].BackColor = System.Drawing.Color.LightBlue;
                    break;

                case "2":
                    for (int i = 5; i &lt; e.Row.Cells.Count; i++)
                        e.Row.Cells[i].BackColor = System.Drawing.Color.LightYellow;
                    break;

                case "3":
                    for (int i = 5; i &lt; e.Row.Cells.Count; i++)
                        e.Row.Cells[i].BackColor = System.Drawing.Color.Orange;
                    break;
            }
        }}


        //For inserting checkboxes inside all courses buttons
        protected void GridView1_DataBound(object sender, EventArgs e){
            GridView GridView1 = (GridView)sender;
            foreach (GridViewRow objRow in GridView1.Rows)
            {
                for (int i = 5; i &lt; objRow.Cells.Count; i++){
                    CheckBox chkCheckBox = new CheckBox();
                    objRow.Cells[i].Controls.Add(chkCheckBox);
                    if (objRow.Cells[i].BackColor == System.Drawing.Color.LightGreen)
                        chkCheckBox.Checked = true;
                }

            }
        }


        //For updating the GridView (Save Button)
        protected void btnSave_Click(object sender, EventArgs e)
        {

        }

UPDATE: I modified the btnSave_Click button to be as following:

//For updating the GridView (Save Button)
        protected void btnSave_Click(object sender, EventArgs e)
        {
            GridView GridView1 = (GridView)sender;
            // Are there checked boxes?
            List<int> CheckBoxList = new List<int>();
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                int courseid = (int)GridView1.DataKeys[i][0];
                CheckBox checkBox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox");
                if (checkBox.Checked)
                {
                    CheckBoxList.Add(courseid);
                }
            }
        }

But I got the following error: Sys.WebForms.PageRequestManagerServerErrorException: Unable to cast object of type 'System.Web.UI.WebControls.Button' to type 'System.Web.UI.WebControls.GridView'

I don't know why I got this error. Could anyone help me with this?

Glory Raj
  • 17,397
  • 27
  • 100
  • 203
Mohammed Al-Ali
  • 75
  • 2
  • 10

3 Answers3

0

Invalid cast in btnSave_Click. The sender variable has reference of Button object. You have to use Repeater.Items collection to access the GridView object.

Your code should be:

protected void btnSave_Click(object sender, EventArgs e)
 {
   for(int i=0;i<Repeater1.Items.Count;i++)
    {            
        GridView GridView1 = (GridView)Repeater1.Items[i].FindControl("GridView1");
        List<int> CheckBoxList = new List<int>();
        for (int i = 0; i < GridView1.Rows.Count; i++)
         {
             int courseid = (int)GridView1.DataKeys[i][0];
             CheckBox checkBox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox");
             if (checkBox.Checked)
              {
               CheckBoxList.Add(courseid);
              }
           }
        }
   }
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • Thanks for your help, but I got an error: Sys.WebForms.PageRequestManagerServerErrorException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index. I don't know I got this error, too. Could you please help me with this issue? – Mohammed Al-Ali Dec 10 '11 at 11:16
  • @MohammedAl-Ali - I haven't tested code in my post. I can suggest you based upon the code you have posted. – KV Prajapati Dec 10 '11 at 11:18
0
         protected void btnSaveRankChanges_Click(object sender, EventArgs e)
            {
                foreach (GridViewRow grv in GridViewRankChanges.Rows)
                {
                    CheckBox changeRankCheck = (CheckBox)grv.Cells[0].FindControl("CheckBoxRankChange");
    if (changeRankCheck != null && changeRankCheck.Checked == true)
         {
              //Do your work for selected checkbox
        }
    }
}

Hope it helps.

Neha
  • 2,933
  • 3
  • 19
  • 23
  • Since I am a new ASP.NET developer, could you please explain to me what do you mean by (FindControl("CheckBoxRankChange");)? – Mohammed Al-Ali Dec 10 '11 at 11:24
  • In your case it is chkSelect used in findcontrol – Neha Dec 10 '11 at 11:28
  • I did not give the checkbox any id because I inserted them in the code-behind as shown above. Please review it – Mohammed Al-Ali Dec 11 '11 at 04:18
  • Also, your code did not work with me. Sorry for asking a lot but I am a new developer and I am trying to do what I watched in the tutorials, so it is too hard for me to grab all of these concepts and information. – Mohammed Al-Ali Dec 11 '11 at 04:23
  • 'protected void btnSave_Click(object sender, EventArgs e) { GridView GridView1 = (GridView)sender;}' the sender is button not gridview means the click event fired by button and you are using sender as gridview – Neha Dec 12 '11 at 04:46
0

In visual basic .net we often used to loop through the grid view. for example

Privtae Sub Button1_Click(sender As Object, e As System.EventArgs)
   Dim rows as gridviewrows

   For Each rows in gridview1.rows
     dim chkbox as new checkbox

      'since we find specific control with unique id so we use to find that control by        
      'using the method FindControl

      chkbox = rows.findcontrol("chkInGridview")

      if chkbox.checked then
         'your code goes here
      else
         'your code goes here
      end if

   Next
End Sub

P/S:

You solve this in many ways. you may try using nested gridview.

mrjurin
  • 136
  • 2
  • 8