samrat matte samrat matte - 3 years ago 78
ASP.NET (C#) Question

How to populate database table from a gridview?

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?

Answer Source

ok, here you go: in code behind do a foreach loop over grid view rows, like this:

    foreach (GridViewRow rw in GridView1.Rows)
    {
        var o = new Object //in your case Booking object
        {
            Id = Convert.ToInt32(GridView1.DataKeys[rw.RowIndex].Value),
            Field1 = rw.Cells[1].Text.ToString(),
            Field2 = Convert.ToInt32(rw.Cells[2].Text.ToString())
        }

        using (var context = new YourEntities())
        {
            //here you save a new row in the database
            context.TestDetail.Add(o);
            context.SaveChanges();
        }
    }

Or with a normal insert sql statement:

    foreach (GridViewRow row in GridView1.Rows)
{
    con.Open();
    SqlCommand cmd1 = new SqlCommand("INSERT INTO Bookings (ID, labID, srNo, test_id) VALUES (@Id1,@lab_id,@serialNo,@testID)", con);
    cmd1.Parameters.AddWithValue("@Id1", orderID);
    cmd1.Parameters.AddWithValue("@lab_id", row.Cells[1].Text);
    cmd1.Parameters.AddWithValue("@serialNo", row.Cells[2].Text);
    cmd1.Parameters.AddWithValue("@testID", row.Cells[3].Text);
    cmd1.ExecuteNonQuery();
}

i wrote this code on fly. you need ofcourse to make it cleaner and takecare of closing connection and disposing objects

If it helps. mark as answer :)!! Cheers!!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download