开发者

ASP.NET grid in 2.0 having trouble with paging to retain value of check box on save button click

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

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开发者_如何学Python)
                {
                    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);
        }

    }

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

        //}

    }

following is the grid view

   <%@ 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>

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 :- 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]; 
}
 }
 }

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


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

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

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜