Click here to Skip to main content
15,167,677 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do you upload the data From GridView and store in database if we have some controls like DropDownLists,TextBoxes,RadioButtons included in it?

Here Is Code
When A of Button Click to upload the data to Database from GridView

C#
protected void Button2_Click(object sender, EventArgs e)
    {
        int i;
        for (i = 0; i < gridview2.Rows.Count; i++)
        {
            SqlCommand cmd = new SqlCommand("insert into rep values('"+gridview2.Rows[i].Cells[0].Text+"','" + gridview2.Rows[i].Cells[1].Text +"','" + gridview2.Rows[i].Cells[2].Text+ "','"+ gridview2.Rows[i].Cells[3].Text+ "')", con);

            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();

        }



Here + gridview2.Rows[i].Cells[2].Text+ is a dropdownlist

and

+gridview2.Rows[i].Cells[3].Text+ is a TextBoxes


Please post the answers.
Posted
Updated 13-Jul-10 6:17am
v3

con doesn't appear to be in this scope, unless you're using it at a form level. Which is not really good practice.

I would recommend building up objects to store the values, then passing that object collection to a method that takes care of writing the data out.

Build up your command objects in a list. Open the DB, then execute the commands, then close the DB.

If this data is critical to be stored atomically you should wrap the operation in a transaction.

You should also use a try...catch block.

Alternatively, consider a DAL framework which takes care of most of this for you.

Cheers.
   
Well, for learning stuff (as beginners), in such cases, you shouldn't try to extract the values directly while formming query.

Instead, break it into two steps. First one, get all the values in a local variable or so and then in second step, use those variables in your query.

As you learn more, you will come to know about parameterized queries and object models that will help more.
   
Building on what Mr James and Sandeep said, I noticed that this is a web application. You should also take into consideration protecting your database against SQL injections and discontinue the use of embedded SQL statements in your code. Instead, build a stored procedure and call that in your SQLCommand, passing in your data values via SQL Parameters.
   

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