Hi,
I have a .NET page which has a gridview of customers from Northwind
database. There's a checkbox for each customer and the gridview allows
paging.
I would like to be able to persist the checkbox status while paging. I'm
starting with the code below but I can't get it to work. You can check some
of the checkboxes and when you click on the pager, no selection is reflected
by the trace. Why's that?
Thanks,
ywb
//***********************************************
<%@ Page Language="C#" Trace="true" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected SqlConnection myConnect;
protected SqlDataAdapter myDataAdapter;
protected SqlCommand myCommand;
protected DataSet myDataSet;
protected void Page_Load(object sender, EventArgs e)
{
myConnect = new
SqlConnection("server=(local);database=Northwind;u id=sa;pwd=;");
BindData();
}
private void BindData()
{
string sqlQuery = "SELECT * FROM Customers";
myDataAdapter = new SqlDataAdapter(sqlQuery, myConnect);
myDataSet = new DataSet();
myDataAdapter.Fill(myDataSet);
GvwCustomers.DataSource = myDataSet;
GvwCustomers.DataBind();
}
private void FindSelections()
{
foreach (GridViewRow row in GvwCustomers.Rows)
{
string customerID = GvwCustomers.DataKeys[row.RowIndex].Value.ToString();
CheckBox cbx = (CheckBox)row.FindControl("CbxSelected");
if (cbx.Checked)
Trace.Warn(customerID + " is selected");
else
Trace.Warn(customerID + " is NOT selected");
}
}
protected void GvwCustomers_PageIndexChanging(object sender,
GridViewPageEventArgs e)
{
FindSelections();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Paging with Checkboxes</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GvwCustomers" runat="server" DataKeyNames="CustomerID"
AllowPaging="true"
AutoGenerateColumns="False"
OnPageIndexChanging="GvwCustomers_PageIndexChangin g">
<Columns>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:CheckBox ID="CbxSelected" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="ID" DataField="CustomerID" />
<asp:BoundField HeaderText="Name" DataField="ContactName" />
<asp:BoundField HeaderText="Title" DataField="ContactTitle" />
</Columns>
</asp:GridView>
</form>
</body>
</html>
//***********************************************