Question

Following query is not inserting value in database.

Code:

 try
 {
      for (int i = 0; i < listViewSubject.Items.Count; i+=2)
      {
           string query = "INSERT INTO Std_Subjects (subject_id, std_reg_id) VALUES ('" + listViewSubject.Items[i] + "', '" + this.reg_id + "')";
           dal.InsertUpdateDelete(query);
      }
      conn.Close();
 }
 catch (Exception ex)
 {
       MessageBox.Show(ex.ToString());
 }
Was it helpful?

Solution

From your question I understand the issue is error with converting to int.You have to convert subject ID to int before inserting.

    Try
        {
        for (int i = 0; i < listViewSubject.Items.Count; i+=2)
        {
            string query = "INSERT INTO Std_Subjects (subject_id, std_reg_id) VALUES (" + Int.Parse(listViewSubject.Items[i].Text) + ", " + this.reg_id + ")";
            dal.InsertUpdateDelete(query);
        }
        conn.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }

Hope this.reg_id is also int. If not convert it as I converted the subject id. Please note that I have removed single quote from

'" + listViewSubject.Items[i] + "', '" + this.reg_id + "'

This is the method using parameterized query:

  for (int i = 0; i < listViewSubject.Items.Count; i+=2)
        {

         string query = "INSERT INTO Std_Subjects (subject_id, std_reg_id) VALUES (@subjectID,@StdRegId)";
         SqlCommand command = new SqlCommand(query, connection);
         command.Parameters.AddWithValue("@subjectID",Int.Parse(listViewSubject.Items[i].Text));
         command.Parameters.AddWithValue("@StdRegId", this.reg_id);
         command.ExecuteNonQuery();
        }

OTHER TIPS

It seems like listViewSubject.Items[i] returns a value 'ListViewItem:{2}' rather than an integer. Depending on what kind of object your item collection returns you may want to debug it. Probably listViewSubject.Items[i].Value might work.

I am not sure exactly what your data access layer does behind the scenes, but using the basic SqlCommand I would be inclined to do your insert as follows:

string sql = "INSERT INTO Std_Subjects (subject_id, std_reg_id) VALUES (@SubjectID, @RegID)";
for (int i = 0; i < listViewSubject.Items.Count; i+=2)
{
    using (var conn = new SqlConnection(ConnectionString))
    using (var command = new SqlCommand(sql, connection))
    {
        conn.Open();
        command.Parameters.Add("@RegID", SqlDbType.Int).Value = this.reg_id;
        command.Parameters.Add(SubjectID, SqlDbType.Int).Value = listViewSubject[i].Text;
        command.ExecuteNonQuery();

    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top