Here is complete source code for insertion and deletion from gridview to database using checkbox.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Label1.Text = Session["projectname"].ToString();
GridBind();
}
else
{
//Response.Write("Postbac occurs");
}
}
public void GridBind()
{
DataTable dt = new DataTable();
string Sql = "SELECT CAST(CASE WHEN EXISTS (SELECT 1 FROM ADMINTAB WHERE USERNAME=B.USERNAME AND ISNULL(PROJECTNAME,'')=ISNULL('" + Label1.Text + "',''))THEN 'TRUE' ELSE 'FALSE' END AS BIT)AS CHK,* FROM admin B";
SqlConnection conn = new SqlConnection(@"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=SUJAY;Data Source=SUPREME6-PC");
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter(Sql, conn);
adp.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("adminame"), new DataColumn("projectname")});
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkval1 = (row.Cells[0].FindControl("chkval1") as CheckBox);
if (chkval1.Checked == true)
{
string adminame = (row.Cells[1].FindControl("Label1") as Label).Text;
string projectname = Label1.Text;
dt.Rows.Add(adminame, projectname);
SqlConnection conn = new SqlConnection(@"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=SUJAY;Data Source=SUPREME6-PC");
conn.Open();
String s = "Insert into admintab values('" + adminame + "','" + projectname + "')";
SqlCommand cmd = new SqlCommand(s, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
else
{
string adminname = (row.Cells[1].FindControl("Label1") as Label).Text;
string projectname = Label1.Text;
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection(@"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=SUJAY;Data Source=SUPREME6-PC");
conn.Open();
////var P_id = ds.Tables[0].Rows[1]["username"].ToString();
SqlCommand cmd = new SqlCommand("Delete from admintab where projectname='"+projectname+"'", conn);
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
}