ASP.NET电网2.0具有分页的麻烦保留在保存按钮,点击复选框值 [英] ASP.NET grid in 2.0 having trouble with paging to retain value of check box on save button click

查看:157
本文介绍了ASP.NET电网2.0具有分页的麻烦保留在保存按钮,点击复选框值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的按钮单击code填补网格视图

this is my button click code which fills the grid view

protected void Btnok_Click(object sender, EventArgs e)
    {

        try
        {
            if (Page.IsValid)
            {
                int passoutYear = Convert.ToInt32(passout.SelectedValue);
                int courseList = Convert.ToInt32(course.SelectedValue);
                StringBuilder sb = new StringBuilder();
                string sep = "";




                foreach (ListItem li in Branch.Items)
                {
                    if (li.Selected)
                    {
                        sb.Append(sep + li.Value);
                        sep = ",";
                    }
                }

                DataTable dt = placedStudentManager.GetPlacedStudentList(sb, passoutYear, courseList);
                if (dt != null && dt.Rows.Count != 0)
                {
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                    GridView1.Visible = true;
                    Btnsave.Visible = true;
                    ViewState["dt"] = dt;
                }
                else 
                {
                    noRecordExistOnOkButton.Text = "No Record Exist To Be Inserted For Recruited Students";
                    Btnsave.Visible = false;
                    GridView1.Visible = false;
                }
            }
        }
        catch (Exception ex)
        {
            COMMON.logger.Error("Error On Button Btnok_Click:CompanySelected.aspx.cs ", ex);
        }
    }

这是我的按钮来保存它保存选中的复选框gridRow在数据库

this is my button save which save the checked check box gridRow in data base

 protected void Btnsave_Click(object sender, EventArgs e)
    {

        try
        {
            if (Page.IsValid)
            {
                int passoutYear = Convert.ToInt32(passout.SelectedValue);
                int companyId = Convert.ToInt32(company.SelectedValue);
                int courseId = Convert.ToInt32(course.SelectedValue);
                string package = txtpackage.Text.Trim();
                string venu = txtvenue.Text.Trim();

                DateTimeFormatInfo dateInfo = new DateTimeFormatInfo();
                dateInfo.ShortDatePattern = "dd/MM/yyyy";
                DateTime date = Convert.ToDateTime(vistDate.Text.Trim(), dateInfo);

                DataTable gridviewTbl = new DataTable();
                DataColumn dc1 = new DataColumn("company_id");
                DataColumn dc2 = new DataColumn("course_id");
                DataColumn dc3 = new DataColumn("branch_id");
                DataColumn dc4 = new DataColumn("student_enrollment");
                DataColumn dc5 = new DataColumn("company_visit_date");
                DataColumn dc6 = new DataColumn("venu");
                DataColumn dc7 = new DataColumn("package");
                DataColumn dc8 = new DataColumn("passout_year");
                gridviewTbl.Columns.Add(dc1);
                gridviewTbl.Columns.Add(dc2);
                gridviewTbl.Columns.Add(dc3);
                gridviewTbl.Columns.Add(dc4);
                gridviewTbl.Columns.Add(dc5);
                gridviewTbl.Columns.Add(dc6);
                gridviewTbl.Columns.Add(dc7);
                gridviewTbl.Columns.Add(dc8);

                if (GridView1 != null && GridView1.Rows.Count != 0)
                {
                    int rowCount = GridView1.Rows.Count;
                    int i = 0;
                    foreach (GridViewRow row in GridView1.Rows)
                    {

                        CheckBox cb = (CheckBox)row.FindControl("Chek");

                        if (cb != null && cb.Checked)
                        {
                            string enrollmetNo = GridView1.Rows[i].Cells[1].Text.ToString();
                            int branchId = Convert.ToInt32(GridView1.DataKeys[0].Value);
                            gridviewTbl.Rows.Add(companyId, courseId, branchId, enrollmetNo, date, venu, package, passoutYear);
                        }
                        i++;
                    }

                    if (gridviewTbl.Rows.Count != 0)
                    {
                        Boolean b = placedStudentManager.SaveSelectdStudent(gridviewTbl);
                        gridNotExist.Text = "Records Successfully inserted";
                    }

                    else
                    {
                        gridNotExist.Text = "Please check the record to be inserted";
                        Btnsave.Visible = true;
                        GridView1.Visible = true;
                    }
                }
                else
                {
                    gridNotExist.Text = "Please Select The Recruited Student, so click the ok button first ";
                }

            }
            else 
            {
                GridView1.Visible = true;
                Btnsave.Visible = true;
            }
        }
        catch (Exception ex)
        {
            COMMON.logger.Error("Error On Button Btnsave_Click:CompanySelected.aspx.cs ", ex);
        }

    }

我现在用做寻呼以下code

now i am doing paging using following code

 protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {

        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataSource = (DataTable)ViewState["dt"];
        GridView1.DataBind();
        GridView1.Visible = true;
        Btnsave.Visible = true;
       // StringBuilder str=(StringBuilder)ViewState["chk"];
        //foreach (GridViewRow row in GridView1.Rows) 
        //{ 

        //}

    }

以下是网格视图

   <%@ Page Language="C#" MasterPageFile="~/Master Pages/AdminMaster.master" AutoEventWireup="true"
    CodeFile="CompanySelected.aspx.cs" Inherits="Admin_CompanySelected"  Trace="false"  Title="Untitled Page"  EnableEventValidation="false" %>


<asp:Content ID="Content1" ContentPlaceHolderID="cph1" runat="Server">

    <script language="javascript" type="text/javascript">

    function BranchCheckBoxCheck(source, args)
    {
      var chkBoxListId=document.getElementById ('<%=Branch.ClientID%>');
      var chkList=chkBoxListId.getElementsByTagName("input");
      for(var i=0;i<chkList.length;i++)
                {  
                    if(chkList[i].checked)
                    {
                        args.IsValid = true;
                        return;
                    }
                }
              args.IsValid = false;
    }
</script>

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cphMain" runat="Server">
    <div border="1">
        <table id="TABLE1" onclick="return TABLE1_onclick()" align="center">
            <tr>
                <td style="height: 24px">
                    Passout Year*</td>
                <td style="height: 24px">
                    <asp:DropDownList ID="passout" runat="server">
                    </asp:DropDownList>
                    <asp:CustomValidator ID="validateYearForSaveButton" runat="server" ControlToValidate="passout"
                        ErrorMessage="insert passout year" OnServerValidate="validateYearForSaveButton_ServerValidate"
                        ValidationGroup="save"></asp:CustomValidator></td>
                <td style="height: 24px">
                <asp:CustomValidator ID="passoutYearRequire" runat="server" ErrorMessage="Passout Year is Compulsory" ControlToValidate="passout" ValidationGroup="verify" OnServerValidate="passoutYearRequire_ServerValidate">
                </asp:CustomValidator>
                </td>
                <td style="width: 101px; height: 24px;">
                </td>
                <td style="width: 126px; height: 24px">
                </td>
                <td style="height: 24px">
                </td>
                <td style="height: 24px">
                </td>
            </tr>
            <tr>
                <td>
                    Company Name*</td>
                <td>
                    <asp:DropDownList ID="company" runat="server">
                    </asp:DropDownList>
                    </td>
                <td>
                    &nbsp;<asp:CustomValidator ID="selectComapnyForSaveButton" runat="server" ControlToValidate="company"
                        ErrorMessage="Select A Company" OnServerValidate="selectComapnyForSaveButton_ServerValidate"
                        ValidationGroup="save"></asp:CustomValidator></td>
                <td style="width: 101px">
                    Package*</td>
                <td style="width: 126px">
                    <asp:TextBox ID="txtpackage" runat="server" Width="197px"></asp:TextBox></td>

                <td>
                <asp:RequiredFieldValidator ControlToValidate="txtpackage" ValidationGroup="save" ID="packageRequire" runat="server" ErrorMessage="Package Require"></asp:RequiredFieldValidator>
                </td>
                <td>
                    <asp:Button ID="Btnok" runat="server" Text="Ok" Width="43px" OnClick="Btnok_Click" ValidationGroup="verify" /></td>
            </tr>
            <tr>
                <td>
                    Course*</td>
                <td>
                    <asp:UpdatePanel id="update" runat="server">
                        <contenttemplate>
                        <asp:DropDownList ID="course" runat="server" AutoPostBack="True" OnSelectedIndexChanged="course_SelectedIndexChanged">
                        </asp:DropDownList>
                         </contenttemplate>
                    </asp:UpdatePanel><asp:CustomValidator ID="coursenecessaryForSaveButton" runat="server"
                        ControlToValidate="course" ErrorMessage="Select A Course" OnServerValidate="coursenecessaryForSaveButton_ServerValidate"
                        ValidationGroup="save"></asp:CustomValidator></td>
                <td>
                    <asp:CustomValidator ID="courseNecessary" runat="server" ErrorMessage="Select A Course"
                        OnServerValidate="courseNecessary_ServerValidate" ValidationGroup="verify"></asp:CustomValidator></td>
                <td style="width: 101px">
                    Branch Name*</td>
                <td style="width: 126px">
                    <asp:UpdatePanel id="upchak" runat="server">
                        <contenttemplate>
<asp:CheckBoxList id="Branch" runat="server" OnSelectedIndexChanged="Branch_SelectedIndexChanged">
                    </asp:CheckBoxList> 
</contenttemplate>
                    </asp:UpdatePanel>
                </td>
                <td>
                <asp:CustomValidator id="branchRequire" runat="server" ValidationGroup="verify" ClientValidationFunction="BranchCheckBoxCheck" ErrorMessage="Select A Branch"></asp:CustomValidator>
               <asp:CustomValidator id="branchrequireForSaveButton" runat="server" ValidationGroup="save" ClientValidationFunction="BranchCheckBoxCheck" ErrorMessage="Select A Branch"></asp:CustomValidator>
              <%-- <asp:CustomValidator ID="branchNotexist" runat="server" ErrorMessage="No Branch Exist" ValidationGroup="verify"  ControlToValidate="Branch" OnServerValidate="branchNotexist_ServerValidate"></asp:CustomValidator>--%>
                </td>
                <td>
                    <asp:Button ValidationGroup="save" ID="Btnsave" runat="server" Text="Save" OnClick="Btnsave_Click" />
                </td>
            </tr>
            <tr>
                <td>
                    Company Visit Date*</td>
                <td>
                    <asp:TextBox ID="vistDate" runat="server" ></asp:TextBox>
                    </td>
                <td>
                    <asp:RequiredFieldValidator ID="dateForSaveButton" runat="server" ControlToValidate="vistDate"
                        ErrorMessage="Visit Date Require" ValidationGroup="save"></asp:RequiredFieldValidator></td>
                <td style="width: 101px">
                </td>
                <td style="width: 126px">
                    <asp:Label ID="noRecordExistOnOkButton" runat="server" Text="Label" Width="178px"></asp:Label></td>
                <td>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td>
                    Venue*
                </td>
                <td>
                    <asp:TextBox ID="txtvenue"  runat="server"></asp:TextBox>
                </td>
                <td colspan="4">
                    <asp:RequiredFieldValidator ID="venRequire" runat="server" ControlToValidate="txtvenue"
                        ErrorMessage="Insert venu" ValidationGroup="save" Width="73px"></asp:RequiredFieldValidator>
                    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp;
                    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
                    <asp:Label ID="gridNotExist" ForeColor="Red" runat="server" Width="439px"></asp:Label></td>
                <td>
                    </td>
            </tr>
            <tr>
                <td colspan="5" style="height: 16px">
                </td>
            </tr>
            <tr>
                <td colspan="5">



<asp:GridView id="GridView1" AllowSorting="true" EnableViewState="true" AutoGenerateColumns="false" runat="server" AllowPaging="True"  DataKeyNames="branch_id, default_check, student_id"   OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="2">

<Columns>
<asp:TemplateField HeaderText="Select Student">
<ItemTemplate>
<asp:CheckBox id="Chek"  runat="server" Text="select" ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Enrollment No." DataField="enrollment_no" />
<asp:BoundField HeaderText="Course Name" DataField="course_name"/>
<asp:BoundField  HeaderText="Branch Name"  DataField="branch_name"/>
<asp:BoundField HeaderText="Email Id" DataField="email" />
<asp:BoundField  HeaderText="Mobile" DataField="mobile"/>
<asp:BoundField HeaderText="Name"  DataField="first_name"/>
<asp:BoundField  HeaderText="Surname" DataField="last_name" />
</Columns>


</asp:GridView> 
                </td>
            </tr>
  <tr>
  <td>
  </td>
  </tr>
        </table>
    </div>
    <br />
    <br />
    <br />
    <br />
    &nbsp;&nbsp;
    <br />
    <br />
    <br />
</asp:Content>

现在我想要做的分页没有松动复选框的状态,并要保存selectd复选框排在保存按钮,单击如何实现这一点,请让我知道数据的基础上。
我使用的点网框架2.0 ...

now i want to do paging without loosing check box state and want to save the selectd check box row in data base on save button click how to achieve this please let me know . I am using dot net framework 2.0...

@PhilPursglove: - 我的解决方案是这样的。

@PhilPursglove :- My solution is like this

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) 
{ Response.Write(GridView1.PageIndex.ToString()); 
int d = GridView1.PageCount; bool[] values = new bool[GridView1.PageSize];
 CheckBox chb; 
for (int i = 0; i < GridView1.Rows.Count; i++) 
{ 
chb = (CheckBox)GridView1.Rows[i].FindControl("Chek"); 
if (chb != null) 
{
 values[i] = chb.Checked; 
} 
}
Session["page" + GridView1.PageIndex] = values;
GridView1.PageIndex = e.NewPageIndex; 
GridView1.DataSource = (DataTable)ViewState["dt"]; 
GridView1.DataBind(); GridView1.Visible = true; Btnsave.Visible = true; 
} 

protected void GridView1_PreRender(object sender, EventArgs e) 
{ 
if (Session["page" + GridView1.PageIndex] != null) 
{ CheckBox chb; bool[] values = (bool[])Session["page" + GridView1.PageIndex]; 
for (int i = 0; i < GridView1.Rows.Count; i++) 
{ chb = (CheckBox)GridView1.Rows[i].FindControl("Chek"); 
chb.Checked = values[i]; 
}
 }
 }

现在我想在保存按钮的选定chkbox行值保存到数据库

now i want on save button to store those selected chkbox row values to database

推荐答案

首先,请允许我重申这个问题,我理解这一点。你有一个分页的GridView有它的复选框。您可以选择一些复选框,然后移动到不同的页面。当你回到原来的页面,你要还是被检查的复选框。

First of all, let me restate the problem as I understand it. You have a paged Gridview that has checkboxes on it. You select some of the checkboxes, then move to a different page. When you come back to the original page, you want those checkboxes to still be checked.

有两个元素来这样做,保存旧页面上的复选框状态,然后在新页面上设置的复选框状态。

There are two elements to doing this, saving the CheckBox state on the old page, and then setting the Checkbox state on the new page.

旧页面上保存复选框状态

Saving the CheckBox state on the old page

有关GridView中的每行,我们需要检查的复选框,看它是否已选中。如果被选中,我们记录数据ID(从 DataKeys )到一个列表。如果未选中它,但它是previously,我们从列表中删除该id。我们所做的每一行之后,我们将保存在ViewState中的列表中。

For every row in the gridview, we need to examine the checkbox to see if it's checked. If it is checked, we record the data id (from DataKeys) into a List. If it isn't checked but it was previously, we remove that id from the list. After we've done this for every row, we save the list in Viewstate.

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    List<int> selectedList;

    selectedList = (List<int>)this.ViewState["selectedList"];
    if (selectedList == null)
    {
        selectedList = new List<int>();
    }

    foreach (GridViewRow row in Gridview1.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            CheckBox rowCheckBox;
            int rowId;

            // Get the Id
            rowId = (int)Gridview1.DataKeys[row.RowIndex].Value;

            // Get the CheckBox
            rowCheckBox = (CheckBox)row.FindControl("Chek");

            if (rowCheckBox.Checked)
            {
                // Don't add the id if it's already in the list
                if (selectedList.Contains(rowId))
                { }
                else
                {
                    selectedList.Add(rowId);
                }
            }
            else
            {
                // Remove the id if it was there but now we've unchecked the box
                if (selectedList.Contains(rowId))
                {
                    selectedList.Remove(rowId);
                }
            }
        }
    }

    // Save the list into viewstate
    this.ViewState["selectedList"] = selectedList;

    // Do the paging as normal
    GridView1.PageIndex = e.NewPageIndex;
    GridView1.DataSource = (DataTable)ViewState["dt"];
    GridView1.DataBind();
    GridView1.Visible = true;
    Btnsave.Visible = true;
}

在新页面上设置复选框状态

Setting the CheckBox state on the new page

现在我们正处在一个新的页面,因为我们数据绑定的每一行,我们需要检查是否复选框需要检查。要做到这一点,我们将获取列表出来视图状态和我们一样绑定的每一行,我们看看如果该行的关键是在列表present - 如果是这样,我们检查的复选框。首先,我们需要这种方法连接到GridView:

Now we're in a new page, as we databind each row we need to examine whether the Checkbox needs to be checked. To do this we will get the list out of Viewstate and as we bind each row we look to see if the key for the row is present in the list - if it is, we check the Checkbox. First off we need to attach this method to the Gridview:

<asp:GridView id="GridView1"  OnRowDataBound="Gridview1_RowDataBound" 
...

protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    List<int> selectedList;
    int rowId;
    CheckBox rowCheckBox;

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        selectedList = (List<int>)this.ViewState["selectedList"];

        if (selectedList == null)
        { }
        else
        {
            rowCheckBox = (CheckBox)e.Row.FindControl("Chek");

            // Get the id for the row
            rowId = (int)Gridview1.DataKeys[e.Row.RowIndex].Value;

            // If the row Id is in the list then check the CheckBox
            if (selectedList.Contains(rowId))
            {
                rowCheckBox.Checked = true;
            }
        }
    }
}

您现在应该能够在页面之间移动,你的复选框会持续:-)

You should now be able to move between pages and your checkboxes will be persistent :-)

目前,您单击保存按钮的时候,我猜想,你要删除从视图状态列表( this.ViewState.Remove(selectedList))让您重置所有内容。这YOUNEED要注意的这里唯一的另一件事是我的演示code这里是根据的DataKeyNames 使用单场为GridView,而你正在使用三个字段,所以你可能会想只选择一个字段用于名单 - 我怀疑studentId会做你想做的如

At the point where you click your Save button, I would guess that you want to remove the List from Viewstate (this.ViewState.Remove("selectedList")) so that you reset everything. The only other thing that youneed to be aware of here is that my demo code here is based on using a single field in DataKeyNames for the Gridview whereas you're using three fields, so you'll probably want to pick just one field to use for the list - I suspect studentId will do what you want e.g.

rowId = (int)Gridview1.DataKeys(row.RowIndex).Values["studentId"];

当您点击保存按钮,您需要再次获取列表出来视图状态,添加任何检查行把它从当前页面,然后用它来生成你的数据表传递给你的经理对象。

When you click your Save button, you need to get the list out of viewstate again, add any checked rows into it from the current page, and then use that to generate your datatable to pass to your manager object.

protected void Btnsave_Click(object sender, EventArgs e)
{
    List<int> selectedList;

    selectedList = (List<int>)this.ViewState["selectedList"];
    if (selectedList == null)
    {
        selectedList = new List<int>();
    }

    foreach (GridViewRow row in Gridview1.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            CheckBox rowCheckBox;
            int rowId;

            // Get the Id
            rowId = (int)Gridview1.DataKeys[row.RowIndex].Value;

            // Get the CheckBox
            rowCheckBox = (CheckBox)row.FindControl("Chek");

            if (rowCheckBox.Checked)
            {
                // Don't add the id if it's already in the list
                if (selectedList.Contains(rowId))
                { }
                else
                {
                    selectedList.Add(rowId);
                }
            }
            else
            {
                // Remove the id if it was there but now we've unchecked the box
                if (selectedList.Contains(rowId))
                {
                    selectedList.Remove(rowId);
                }
            }
        }
    }

    int passoutYear = Convert.ToInt32(passout.SelectedValue);
    int companyId = Convert.ToInt32(company.SelectedValue);
    int courseId = Convert.ToInt32(course.SelectedValue);
    string package = txtpackage.Text.Trim();
    string venu = txtvenue.Text.Trim();

    DateTimeFormatInfo dateInfo = new DateTimeFormatInfo();
    dateInfo.ShortDatePattern = "dd/MM/yyyy";
    DateTime date = Convert.ToDateTime(vistDate.Text.Trim(), dateInfo);

    DataTable gridviewTbl = new DataTable();
    ...

    foreach (int id in selectedList)
    {
        DataRow newStudentRow;
        newStudentRow = gridviewTbl.NewRow;
        newStudentRow[0] = id;
        newStudentRow[1] = courseid;
        ...
        gridviewTbl.Rows.Add(newStudentRow);
    }

    if (gridviewTbl.Rows.Count != 0)
    {
        Boolean b = placedStudentManager.SaveSelectdStudent(gridviewTbl);
        if (b)
        {
            gridNotExist.Text = "Records Successfully inserted";
        }
    }
    else
    {
        gridNotExist.Text = "Please check the record to be inserted";
        Btnsave.Visible = true;
        GridView1.Visible = true;
    }
}

这篇关于ASP.NET电网2.0具有分页的麻烦保留在保存按钮,点击复选框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆