Jade M
Jade M

Reputation: 3101

C# Insert into SQL table is missing the first row from my datagrid

I'm using the code below to insert data into a SQL table from a datagrid, the datagrid has 5 rows but only 4 are inserted into the table, the first row is missed off. I've narrowed the problem to updateTable below. Can you spot the problem? After an hour of trying I can't.

private void updateTable(OdbcConnection conn)
{
                int iCols = _DGV.ColumnCount;
                int iRows = _DGV.RowCount;
                int iIndex = 1;

                string strSql = GetInsertStatement(iCols);

                foreach(DataGridViewRow dr in _DGV.Rows)
                {
                    if (!dr.Visible)
                    {
                        continue;
                    }

                    iIndex++;

                    OdbcCommand cmd = new OdbcCommand();
                    for (int j = 0; j <= iCols - 1; j++)
                    {
                        if (_DGV.Columns[j].Visible == false)
                        {
                            continue;
                        }
                    try
                    {
                        conn.Open();
                        cmd.Connection = conn;
                        cmd.CommandText = strSql;
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {

                    }
                    finally
                    {
                        conn.Close();
                    }
                }
}

Upvotes: 0

Views: 801

Answers (3)

Noah
Noah

Reputation: 19

for (int j = 0; j <= iCols - 1; j++)
{
    if (_DGV.Columns[j].Visible == false)
  {
    continue;
  }
}

j <= iCols - 1; I think here is the problem, try to change that to <= iCols

Upvotes: 0

Jonas
Jonas

Reputation: 4584

Are you sure each row in the grid is visible? IE, at the end of your loop (as it is written), does iIndex == iRows?

Upvotes: 1

lod3n
lod3n

Reputation: 2903

Maybe:

int iIndex = 0;

Upvotes: 0

Related Questions