Click here to Skip to main content
15,886,067 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to insert checked checkbox data from gridview in database.

MY HTML FILE IS LIKE THIS::::
ASP.NET
<pre lang="xml"><asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
          <Columns>
              <asp:TemplateField HeaderText="Id" SortExpression="Id">
                  <EditItemTemplate>
                      <asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("Id") %>'></asp:TextBox>
                  </EditItemTemplate>
                  <ItemTemplate>
                      <asp:Label ID="Label5" runat="server" Text='<%# Bind("Id") %>'></asp:Label>
                  </ItemTemplate>
              </asp:TemplateField>
              <asp:TemplateField HeaderText="Name" SortExpression="Name">
                  <EditItemTemplate>
                      <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
                  </EditItemTemplate>
                  <ItemTemplate>
                      <asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
                  </ItemTemplate>
              </asp:TemplateField>
              <asp:TemplateField HeaderText="EmailId" SortExpression="EmailId">
                  <EditItemTemplate>
                      <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("EmailId") %>'></asp:TextBox>
                  </EditItemTemplate>
                  <ItemTemplate>
                      <asp:Label ID="Label2" runat="server" Text='<%# Bind("EmailId") %>'></asp:Label>
                  </ItemTemplate>
              </asp:TemplateField>
             <%-- <asp:TemplateField HeaderText="Date_Time" SortExpression="Date_Time" Visible="false">
                  <EditItemTemplate>
                      <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Date_Time") %>'></asp:TextBox>
                  </EditItemTemplate>
                  <ItemTemplate>
                      <asp:Label ID="Label3" runat="server" Visible="false" Text='<%# Bind("Date_Time") %>'></asp:Label>
                  </ItemTemplate>
              </asp:TemplateField>--%>
              <asp:TemplateField HeaderText="Checkall" SortExpression="Checkall">
                  <EditItemTemplate>
                      <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Checkall") %>'></asp:TextBox>
                  </EditItemTemplate>
                  <HeaderTemplate>
                      <asp:CheckBox ID="Chkall" runat="server" />
                  </HeaderTemplate>
                  <ItemTemplate>
                      <asp:CheckBox ID="CheckBox1" runat="server" />
                  </ItemTemplate>
              </asp:TemplateField>
          </Columns>




My CODE BEHIND FILE IS LIKE THIS:::


C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    string connStr = ConfigurationManager.ConnectionStrings["TDB"].ConnectionString;
    
    int select;
    
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private void BindGrid()
    {
        Class1 cs = new Class1();
        GridView1.DataSource = cs.DisplayData();
        GridView1.DataBind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        BindGrid();
    }
/// <summary>
/// ///Test insert multiple values////
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>

    protected void Button2_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TDB"].ConnectionString);

        for (int i = 0; i < GridView1.Rows.Count - 1; i++)
        {
            GridViewRow row = GridView1.Rows[i];
            CheckBox cb = (CheckBox)row.FindControl("CheckBox1");
            if (cb.Checked == true)
            {
                select++;
            }
        }
        for (int i = 0; i < GridView1.Rows.Count-1; i++)
        {
           
          //  string Date_Time = GridView1.Rows[i].Cells[4].Text;
            GridViewRow row = GridView1.Rows[i];
            string U_Id = GridView1.Rows[i].Cells[1].Text;
            string Name = GridView1.Rows[i].Cells[2].Text;
            string Email_Id = GridView1.Rows[i].Cells[3].Text;
            CheckBox cb = (CheckBox)row.FindControl("CheckBox1");

            if (cb.Checked == true)
            {
                InsertData(U_Id, Name, Email_Id, System.DateTime.Now.ToString());
            }
         }
        Response.Write("Record inserted successfully");

    }
    void InsertData(string U_Id, string Name, string Email_Id, string Date_Time)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TDB"].ConnectionString);
        try
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("insert into Dashboard values('" + U_Id + "','" + Name + "','" + Email_Id + "','" + Date_Time + "')", con);
            cmd.ExecuteNonQuery();
            con.Close();
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }





    
}


I have insert code and html file??? now pls help me with this cod eand tell me where to change things
Posted
Updated 25-Dec-14 0:27am
v3
Comments
Rajesh waran 25-Dec-14 2:45am    
What you have tried? Paste your code and tell us where you have struck?
Suvendu Shekhar Giri 25-Dec-14 3:05am    
This is a community site. Please paste the code you have tried so far. In case you want to store checked status of the checkbox then it is expected that you may have a column in database with datatype as bit which accepts 1 or 0 corresponding to true and false value.
KaushalJB 25-Dec-14 5:39am    
Unclear !!! Elaborate with your applied code.

Although your code have may concerns, I am writing the snippet which should solve your problem.

Replace this for Button2_Click-

C#
protected void Button2_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TDB"].ConnectionString);
 
        for (int i = 0; i < GridView1.Rows.Count - 1; i++)
        {
            GridViewRow row = GridView1.Rows[i];
            CheckBox cb = (CheckBox)row.FindControl("CheckBox1");
            if (cb.Checked == true)
            {
                select++;
            }
        }
        for (int i = 0; i < GridView1.Rows.Count-1; i++)
        {
           
          //  string Date_Time = GridView1.Rows[i].Cells[4].Text;
            GridViewRow row = GridView1.Rows[i];
            string U_Id = ((TextBox)GridView1.Rows[i].FindControl("TextBox5")).Text;
            string Name = ((TextBox)GridView1.Rows[i].FindControl("TextBox1")).Text;
            string Email_Id = ((TextBox)GridView1.Rows[i].FindControl("TextBox2")).Text;
            CheckBox cb = (CheckBox)Rows[i].FindControl("CheckBox1");
 
            if (cb.Checked == true)
            {
                InsertData(U_Id, Name, Email_Id, System.DateTime.Now.ToString());
                Response.Write("Record inserted successfully");
            }
         }
        
 
    }


In case this doesn't resolve your problem, please let me know :)
 
Share this answer
 
v3
Comments
Parth Mashroo 25-Dec-14 7:06am    
There is aproblem in foreach statement at start whenever i write that code it shows some error.

pls look at that.!!!
thanx for reply!!!
Suvendu Shekhar Giri 25-Dec-14 7:18am    
Thanks ! Updated now. Actually, I had started converting it to foreach loop but later left as it is. Only changes that I have made is to find textbox controls and their values . It should work, otherwise please let me know :)
Parth Mashroo 25-Dec-14 7:26am    
I have tried using for loop and the loop dosent even enter inside if there is only one record and tried your code it shows that data has been inserted sucessfully but id dosent show in table so pls help.!!

if you want i can upload the code in some rar file or something pls let me know if i need to do this!!
Suvendu Shekhar Giri 25-Dec-14 7:33am    
Ok. I think I have figured out few more problems and rectified accordingly. Can you check the solution now please.
Parth Mashroo 25-Dec-14 7:37am    
https://www.dropbox.com/s/jw87mm3bqgwnm5n/Check_Grid.rar?dl=0

this is my file in rar so pls look at this code an tell me how to clear it i am using vs 2012 pls help and i forgot to wish you mery xmas!!
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    string connStr = ConfigurationManager.ConnectionStrings["TDB"].ConnectionString;

    int select;

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private void BindGrid()
    {
        Class1 cs = new Class1();
        GridView1.DataSource = cs.DisplayData();
        GridView1.DataBind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        BindGrid();
    }
    /// <summary>
    /// ///Test insert multiple values////
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>

    protected void Button2_Click(object sender, EventArgs e)
 {
       SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TDB"].ConnectionString);
 foreach (GridViewRow row in GridView1.Rows)
{

Label Id = row.FindControl("Label5")as Label;
Label Name = row.FindControl("Label1")as Label;
Label EmailId = row.FindControl("Label2")as Label;
Label Date_Time = row.FindControl("Label3") as Label;
CheckBox cb = (CheckBox)row.FindControl("CheckBox1");
if (cb.Checked==true)
{
InsertData(Id.Text, Name.Text, EmailId.Text,System.DateTime.Now.ToString());
}

}
 }
public void InsertData(string Id, string Name, string EmailId,string Date_Time)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TDB"].ConnectionString);
        try
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("insert into Test values('" + Id + "','" + Name + "','" + EmailId + "','"+Date_Time+"')", con);
            cmd.ExecuteNonQuery();
            con.Close();
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
 
}
 
Share this answer
 
v2
First Of You have find Check box on button click like below
C#
protected void Button2_Click(object sender, EventArgs e)
   {
       SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TDB"].ConnectionString);

foreach (GridViewRow row in MyGridView.Rows)
    {
      
       TextBox U_Id = row.FindControl("Textbox5")as TextBox;
       TextBox Name = row.FindControl("Textbox1")as TextBox;
       TextBox Email_Id = row.FindControl("Textbox2")as TextBox;
       CheckBox cb = (CheckBox)row.FindControl("CheckBox1");
       if (cb.checked==True)
       {
        InsertData(U_Id, Name, Email_Id, System.DateTime.Now.ToString());
       }
        
    }
}

Public void InsertData(string U_Id, string Name, string Email_Id, string Date_Time)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TDB"].ConnectionString);
        try
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("insert into Dashboard values('" + U_Id + "','" + Name + "','" + Email_Id + "','" + Date_Time + "')", con);
            cmd.ExecuteNonQuery();
            con.Close();
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
 
Share this answer
 
v4
Comments
Parth Mashroo 25-Dec-14 7:08am    
what do you mean by insert struct..

pls write that solution u r mentioning in code thanx for reply...
Tushar sangani 25-Dec-14 7:44am    
insert stuct means write your Querry there
Parth Mashroo 25-Dec-14 7:50am    
sir i tried but isnt working..

pls help
syed shanu 25-Dec-14 19:53pm    
Did you use Break Point and is all your data you get before the call the insert function.

i think this will work.
foreach (GridViewRow row in MyGridView.Rows)
{

TextBox U_Id = row.FindControl("Textbox5")as TextBox;
TextBox Name = row.FindControl("Textbox1")as TextBox;
TextBox Email_Id = row.FindControl("Textbox2")as TextBox;
CheckBox cb = (CheckBox)row.FindControl("CheckBox1");
if (cb.checked==True)
{
InsertData(U_Id.Text, Name.Text, Email_Id.Text, System.DateTime.Now.ToString());
}

}
}
Parth Mashroo 26-Dec-14 0:32am    
https://www.dropbox.com/s/3npuzqli8q1w221/work.JPG?dl=0

it shows error as shown in link

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900