Hi,
i have tried to insert all rows at one time from datagridview c# into a table in database , although the table gets all the rows from datagridview but it always gets the values of the last row from datagridview for all the other rows , so all the rows in the table have the same values . Could anyone help ?

//class Presentation
for(int i=0; i<datagridview1.Rows.Count - 1; i++)
{
ClassPro.ProductA = datagridview1.Row.Cells[0].Value.ToString();
ClassPro.ProductB = datagridview1.Row.Cells[1].Value.ToString();
MyArray.Add(ClassPro);
}

//class Database Access Object
for(int i=0; i<Class.MyArray.Count; i++)
{
string InsertTable = "insert into table_name values('" + Class.MyArray.ProductA + "', '" + Class.MyArray.ProductB + "' )" ;
}

Where is you insert command?

I only see the string.

You need to move the ExecuteNonQuery() in to

for(int i=0; i<Class.MyArray.Count; i++)
{
string InsertTable = "insert into table_name values('" + Class.MyArray[i].ProductA + "', '" + Class.MyArray[i].ProductB + "' )" ;
}

Cause if you run Execute once on the string InsertTable it will only do the last thing where i = Class.MyArray.Count-1

You see what I am saying?

it runs through this code making InsertTable = to the i^th Product A and B.

What you could/should do is.

MyConnection.Open();
for(int i=0; i<Class.MyArray.Count; i++)
{
      new SqlCommand("insert into table_name values('" + Class.MyArray[i].ProductA + "', '" + Class.MyArray[i].ProductB + "' )", MyConnection).ExecuteNonQuery();
}
MyConnection.Close();

or

MyConnection.Open();
for(int i=0; i<Class.MyArray.Count; i++)
{
      string InsertTable = "insert into table_name values('" + Class.MyArray[i].ProductA + "', '" + Class.MyArray[i].ProductB + "' )" ;
      SqlCommand cmd = new SqlCommand();
      cmd.Connection = MyConnection;
      cmd.CommandText= InsertTable;
      cmd.ExecuteNonQuery();
}
MyConnection.Close();

Enjoy.

Hi Finito ,
I coded exactly as you did , but it does not work ( of course i understand the code snippet ). However , thank you for your coding . I will try .

Are you getting an error?

Are the symptoms different?

What is the output?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.