这是我的按钮点击代码,用于填充网格视图
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保存在数据库
中 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);
}
}
现在我正在使用以下代码进行分页
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>
<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>
</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>
<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 />
<br />
<br />
<br />
</asp:Content>
现在我想在不丢失复选框状态的情况下进行分页,并希望保存数据库中选中的复选框行保存按钮单击如何实现这一点请告诉我。 我正在使用dot net framework 2.0 ...
@PhilPursglove: - 我的解决方案是这样的
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行值存储到数据库
答案 0 :(得分:2)
首先,让我按照我的理解重述这个问题。你有一个分页的Gridview,它上面有复选框。您选择一些复选框,然后移动到其他页面。当您返回原始页面时,您仍希望检查这些复选框。
执行此操作有两个要素,在旧页面上保存CheckBox状态,然后在新页面上设置Checkbox状态。
在旧页面上保存CheckBox状态
对于gridview中的每一行,我们需要检查复选框以查看是否已选中它。如果选中它,我们会将数据ID(从DataKeys
)记录到List中。如果未检查但之前已经检查过,我们会从列表中删除该ID。在我们为每一行完成此操作后,我们将列表保存在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;
}
在新页面上设置CheckBox状态
现在我们在一个新页面中,因为我们需要检查每一行,以检查是否需要检查Checkbox。为此,我们将从Viewstate中获取列表,当我们绑定每一行时,我们会查看列中是否存在该行的键 - 如果是,我们检查复选框。首先,我们需要将此方法附加到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;
}
}
}
}
您现在应该可以在页面之间移动,并且您的复选框将是持久的:-)
在您单击“保存”按钮的位置,我猜您要从Viewstate(this.ViewState.Remove("selectedList")
)中删除List,以便重置所有内容。你需要注意的唯一另一件事就是我的演示代码基于在DataKeyNames
中使用Gridview中的单个字段,而你使用的是三个字段,所以你可能只想选择一个字段用于列表 - 我怀疑studentId会做你想要的,例如
rowId = (int)Gridview1.DataKeys(row.RowIndex).Values["studentId"];
当您单击“保存”按钮时,需要再次从视图状态中获取列表,从当前页面将任何选中的行添加到其中,然后使用它来生成要传递给管理器对象的数据表。
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;
}
}