Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
my question depends upon my need to populate a table in database, from a gridview. I've populated that gridview from a datatable from ViewState. Can anybody help me?

What I have tried:

C#
string str = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
                SqlConnection con = new SqlConnection(str);
                con.Open();
                SqlCommand cmd = new SqlCommand("Select TOP 1 * from Bookings", con);
                SqlDataReader reader = cmd.ExecuteReader();
                if(reader.Read())
                {
                    bookingId = Convert.ToInt32(reader["Id"]);
                }

                Booking_Tax(bookingId);//Here I have multiple entries for taxes with same bookingId
Posted
Updated 25-Jul-17 3:05am

1 solution

Hi,

To you insert the records into the database, you need to read each row in the gridview by inserting the records.

Here! An example.

C#
private void Booking_Tax(Int32 id)
        {
            string str = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
            SqlConnection con = new SqlConnection(str);
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;

            //read each row in your gridview
            foreach (GridViewRow gvrow in this.grd_result.Rows)
            { 
                //insert query
                cmd.CommandText = "INSERT INTO mytable (id, tax1, taxt2) VALUE (" + id.ToString() + ", " + gvrow.Cells[0].Text + ", " + gvrow.Cells[2].Text + ")";

                //execute the query for insert record in database
                cmd.ExecuteNonQuery();
            }
        }
 
Share this answer
 
Comments
sam_matte 25-Jul-17 9:34am    
Thanks a Lot!
Sheila Pontes 25-Jul-17 13:09pm    
I'm glad to help you.
sam_matte 26-Jul-17 1:55am    
There's a column in my table which doesn't show up at gridview. Its the first column named "TaxId". I've declared it as datakey on my gridview but,I'm not able to get Value property in "GridView1.DataKeys[rw.RowIndex].Value". It just doesn't shows up at all. Any Fix?
sam_matte 26-Jul-17 2:10am    
Sorry, Got it, I had used "DataKeyNames" instead of "DataKeys" in "GridView1.DataKeys[rw.RowIndex].Value".
Sheila Pontes 26-Jul-17 7:33am    
Hi,

See this post https://www.codeproject.com/Answers/1196181/View-button-in-gridview-corresponding-to-a-user-ca#answer2.

I explain, how to use DataKeyNames in the gridview.

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