ASP.NET - error while uploaded the GridView Control Data To the Other GridView

Asked By aman on 22-Nov-11 01:49 AM
hi all,

i have data in one of the GridView Control which is been exported from the .text file(comma seperated)
and data from that gridview i am storing it to the sql server database like below code snippet but the problem is that the in the first grid view is getting looped and store to sql server twice.

below is the code snippet i have used to store the data from gridview control to the Sql server database table.

        protected void Button3_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(str);
            con.Open();
            foreach (GridViewRow r in GridView2.Rows)
            {
                string studentname = r.Cells[0].Text.ToString();
                string rollno = r.Cells[1].Text.ToString();
                string course = r.Cells[2].Text.ToString();
                try
                {
                    SqlCommand com = new SqlCommand();
                    com.CommandText="insert into Student values('"+studentname+"','"+rollno+"','"+course+"')";
                    //com.Parameters.AddWithValue("@StudentName", studentname);
                    //com.Parameters.AddWithValue("@RollNo", rollno);
                    //com.Parameters.AddWithValue("@Course", course);
                    com.Connection = con;
                    com.ExecuteNonQuery();
                    SqlDataAdapter adap = new SqlDataAdapter(com);
                    DataTable dt = new DataTable();
                    adap.Fill(dt);
                    GridView2.DataSource = dt;
                    GridView2.DataBind();
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
            }
            con.Close();
            BindData(); // This method basically load the data to the GridView1 
        }


please help me....
thanks,
dipa ahuja replied to aman on 22-Nov-11 02:00 AM
Debug your code, and see may be your binding code is executing twice. that's why its getting value twice.
kalpana aparnathi replied to aman on 22-Nov-11 03:53 AM

You need to either set the http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.autogeneratecolumns.aspx to false or not set up the columns.

If you choose the former method your grid definition will become:

<asp:GridView ID="p1" runat="server" Width="520px" AutoGenerateColumns="False">