I have this simple program that will get data out of the database and populate a Gridview. Each row has a checkbox and data from the database. Now when you check of the check box and click the submit button it is suppose to tell me the rows in which the checkbox of that row is checked but it always return all of them. Why is it doing that? I am thinking it might be a postback issue? Here is the code to the CS and ASPX page.
CS
------------
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.
WebParts;
using System.Web.UI.HtmlControls
;
using System.Data.SqlClient;
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//GridView1
//Application["pictureFile
Path"] + "exterior/"
temp();
}
protected void temp()
{
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionStr
ing = ConfigurationManager.Conne
ctionStrin
gs["Connec
tionString
"].Connect
ionString;
SqlCommand myCommand = new SqlCommand("select bathid, model, size, sink, fixture, pic_sm from tblbathroom", myConnection);
myCommand.Connection.Open(
);
SqlDataAdapter da = new SqlDataAdapter(myCommand.C
ommandText
, myConnection);
DataSet ds = new DataSet();
da.Fill(ds);
//close connection
myConnection.Close();
da.Dispose();
this.GridView1.DataSource = ds;
this.GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
CheckBox chkBox = null;
for (int i = 0; i < this.GridView1.Rows.Count;
++i)
{
chkBox = (CheckBox)this.GridView1.R
ows[i].Fin
dControl("
CheckBox1"
);
if (chkBox.Checked)
TextBox1.Text = TextBox1.Text + i;
}
}
}
ASPX
--------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml"
>
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" >
<Columns>
<asp:TemplateField HeaderText="select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat = "server" />
</ItemTemplate></asp:Templ
ateField>
</Columns>
</asp:GridView>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextB
ox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
</form>
</body>
</html>
Start Free Trial