Wednesday, June 17, 2009

Using checkbox in the gridview using c#











using System;
using System.Data;
using System.Configuration;
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.Text;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
cn = new SqlConnection("Data Source=.;Initial Catalog=master;Integrated Security=True");
if (!IsPostBack)
{
pg_load();
}
}

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
StringBuilder str = new StringBuilder();


int i = 0;


//for (int i = 0; i < GridView1.Rows.Count; i++)
//{
// GridViewRow row = GridView1.Rows[i];
// bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;

// if (isChecked)
// {


foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox chk = (CheckBox)gvr.FindControl("chkSelect");
if (chk.Checked==true)
{

str.Append(" "+GridView1.Rows[i].Cells[2].Text);
i++;
}
}


// prints out the result

Response.Write(str.ToString());
}
void pg_load()
{
cmd = new SqlCommand("select * from gridcheck", cn);
cmd.CommandType = CommandType.Text;
da = new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}



No comments:

Post a Comment