2

I wish to insert values from my datagridview into sql server database.I'm not sure whether this works or not but I don't wish to use text boxes.

My logic is to traverse through every cell of datagridview using two for loops(say i and j) but I'm not sure if this work.

Please help..

Davide Piras
  • 43,984
  • 10
  • 98
  • 147
user
  • 75
  • 1
  • 2
  • 7

3 Answers3

0

in one way or another that should be possible, but why do you want to load data from the GridView to the back end instead of loading and consuming the same data you used originally to fill and render the UI control (DataGridView) ?

see my answer here: https://stackoverflow.com/a/7939179/559144 when you have a DataTable you used to bind and show your data in the DataGridView you can easily loop like that, you can then use the edit mode of the grid to capture end user changes in the user interface and process them in the program logic / back end and save changes to the database.

Community
  • 1
  • 1
Davide Piras
  • 43,984
  • 10
  • 98
  • 147
-1

If your application is window app and shows all fields from a table in database, you should use Datagridview with SqlDataAdapter.For example-

private BindingSource bindingSource = null;
private SqlDataAdapter sqlDataAdapter = null;
DataTable dataTable=null;

private void Form_Load(object sender, EventArgs e)
{
     dataTable = new DataTable();
     sqlDataAdapter.Fill(dataTable);//Fill Data To bind Datagridview
     bindingSource = new BindingSource();
     bindingSource.DataSource = dataTable;
     dataGridViewTrial.DataSource = bindingSource;
}

private void btnSave_Click(object sender, EventArgs e)
{
     try
       {
           sqlDataAdapter.Update(dataTable);
       }
       catch (Exception exceptionObj)
          {
             MessageBox.Show(exceptionObj.Message.ToString());
          }
}

See also Here.

nnnn
  • 1,041
  • 3
  • 18
  • 35
  • Hi I found an answer to this....a simpler code which inserts data from datagridview to SQL database. – user Mar 13 '13 at 12:26
-1

Hi I found an answer to this....a simpler code which inserts data from datagridview to SQL database. Please note that your column names are predefined here.

private void button1_Click(object sender, EventArgs e)
    {
        string str = System.Environment.MachineName;
        SqlConnection sconn = new SqlConnection("Data Source='" + str + "';Initial Catalog=main;Integrated Security=True");
        sconn.Open();
        DataSet ds = new DataSet();
        for(int i=0; i< dataGridView1.Rows.Count;i++)
            {
                SqlDataAdapter da = new SqlDataAdapter("insert into demo values('" + dataGridView1.Rows[i].Cells[0].Value + "','" + dataGridView1.Rows[i].Cells[1].Value + "','" + dataGridView1.Rows[i].Cells[2].Value + "')",sconn);
                    da.Fill(ds, "main");




        conn.Close();

}

user
  • 75
  • 1
  • 2
  • 7