【问题标题】:How to update the GridView after checking the checkbox and clicking the save button?选中复选框并单击保存按钮后如何更新 GridView?
【发布时间】:2011-12-10 19:23:38
【问题描述】:

我需要设置这些 GridView 以供管理员更新。所以既然我有 每个GridView里面有很多员工和很多课程,我觉得最好 更新 GridView 的方法是将空白字段显示为复选框以及何时 管理员想要更新其中一名员工的记录,他的所有内容 需要做的只是检查复选框并单击更新按钮。 我可以 能够将空字段显示为复选框,但现在我不知道如何 将选中复选框的值发布到数据库。

我正在寻找的场景是让系统检查每个 每个 GridView 中的复选框,如果之前已经选中,则保持原样 是。如果它是空的并且现在刚刚被检查,它应该被添加到 数据库中的员工记录。因此,GridView 将通过单击保存按钮进行更新。我原来的代码是:

<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 />

背后的代码:

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)
        {

        }

更新: 我修改了 btnSave_Click 按钮如下:

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

但我收到以下错误: Sys.WebForms.PageRequestManagerServerErrorException:无法将“System.Web.UI.WebControls.Button”类型的对象转换为“System.Web.UI.WebControls.GridView”

我不知道为什么会出现这个错误。谁能帮我解决这个问题?

【问题讨论】:

    标签: c# asp.net asp.net-controls


    【解决方案1】:

    btnSave_Click 中的无效转换。 sender 变量引用了 Button 对象。您必须使用Repeater.Items 集合来访问GridView 对象。

    你的代码应该是:

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

    【讨论】:

    • 感谢您的帮助,但出现错误:Sys.WebForms.PageRequestManagerServerErrorException:索引超出范围。必须是非负数且小于集合的大小。参数名称:索引。我不知道我也遇到了这个错误。你能帮我解决这个问题吗?
    • @MohammedAl-Ali - 我没有在我的帖子中测试过代码。我可以根据您发布的代码向您推荐。
    【解决方案2】:
             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
            }
        }
    }
    

    希望对你有帮助。

    【讨论】:

    • 由于我是一名新的 ASP.NET 开发人员,请您解释一下 (FindControl("CheckBoxRankChange");) 是什么意思?
    • 在您的情况下,它是 findcontrol 中使用的 chkSelect
    • 我没有为复选框提供任何 id,因为我将它们插入到代码隐藏中,如上所示。请检查它
    • 另外,您的代码不适用于我。很抱歉问了很多问题,但我是一名新开发人员,我正在尝试做我在教程中看到的内容,所以我很难掌握所有这些概念和信息。
    • 'protected void btnSave_Click(object sender, EventArgs e) { GridView GridView1 = (GridView)sender;}' 发送者是按钮而不是 gridview 表示按钮触发的点击事件,并且您使用发送者作为 gridview
    【解决方案3】:

    在 Visual Basic .net 中,我们经常使用循环遍历网格视图。例如

    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:

    您可以通过多种方式解决这个问题。您可以尝试使用嵌套的gridview。

    【讨论】:

    • op 试图在 C# 中而不是在 vb.net 中进行
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多