problem using for() with datagrid - blank cell value RRS feed

  • Question

  • Hi,

    I am using the following for() to loop through a datagrid to save to a database. My problem here is: when looping, I am getting all records correct except the last record which I am getting a blank cell value for it. what's wrong with my for() please?

    for (int i = 0; i <= gridContacts.RowCount; i++)
        sql_command = new MySqlCommand("sp_add_new_employee_contact", sql_connection);
        sql_command.CommandType = CommandType.StoredProcedure;
        sql_command.CommandTimeout = Convert.ToInt32(string_encryptor.DecryptString(xmlClass.read_xml_value("HRMS\\HRMS", "CommandTimeOut"), "JassimRahma@731004167"));
        sql_command.Parameters.AddWithValue("param_employee_id", employee_id).MySqlDbType = MySqlDbType.Int32;
        sql_command.Parameters.AddWithValue("param_contact_category", Convert.ToInt32(gridContacts.GetRowCellValue(i, "contact_category"))).MySqlDbType = MySqlDbType.Int32;
        sql_command.Parameters.AddWithValue("param_contact_details", Convert.ToString(gridContacts.GetRowCellValue(i, "contact_details"))).MySqlDbType = MySqlDbType.VarChar;
        sql_command.Parameters.AddWithValue("param_contact_description", Convert.ToString(gridContacts.GetRowCellValue(i, "contact_description"))).MySqlDbType = MySqlDbType.VarChar;
        MessageBox.Show(Convert.ToString(gridContacts.GetRowCellValue(i, "contact_details")));
        int result_rows = sql_command.ExecuteNonQuery();


    Saturday, June 14, 2014 10:03 AM


All replies

  • That sounds right. The last row will be an empty new row. There is a property IsNewItem on DataGridRow which you can check for and just ignore the record if it is true.

    Saturday, June 14, 2014 1:59 PM
  • but that's for the new record, what about the last record? as mentioned, if I have two reows then only first row's cell will be shown and the second will be blank although second has value)!
    Sunday, June 15, 2014 6:01 AM
  • You loop condition is incorrect. When looping over zero based arrays, your loop condition shops normally be of the form "i < array.Length".

    Top tip: Wherever possible prefer foreach over for.



    Sunday, June 15, 2014 8:26 AM