num = textBox5.Text; using (OleDbConnection oledb = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\WhiteChemist-PC\source\repos\ГСМ\ГСМ\GSM.accdb")) { oledb.Open(); OleDbCommand command = new OleDbCommand(string.Format($"SELECT (Normaras) FROM [Table] WHERE [Numb] = '{0}'", num), oledb); using (OleDbDataReader dataReader = command.ExecuteReader()) { norma = command.ExecuteScalar().ToString(); if (radioButton1.Checked == true && comboBox2.SelectedIndex == 0) { try { k = int.Parse(norma); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } nadb = (k* (5 / 100)); command = new OleDbCommand(string.Format($"INSERT INTO [Table].[(Nad)] VALUES ('{0}')", nadb.ToString()), oledb); while (dataReader.Read() == true) command.ExecuteNonQuery(); } 

In the line norma=command.ExecuteScalar().ToString() throws an exception:

System.InvalidOperationException: "There is an open DataReader assigned to this command by Command that needs to be closed in advance."

Prior to this, there have never been such errors when working with DB. Who knows what's the matter?

  • One command calls both ExecuteScalar and ExecuteReader . Leave one thing. - Alexander Petrov
  • Oh, until the end of the code did not inspect. You also have a team redefined there. The code to remove, the author to burn (you can do the opposite), then write from scratch. Using using for all Disposable objects (including command). - Alexander Petrov
  • @AlexanderPetrov should not offer to burn and remove someone just because he was a little mistaken in the code. - PashaPash
  • @AlexanderPetrov I understand perfectly that I write a lot of shit code. But you understand if I come up with some kind of beautiful crutch that will work as it should, then in my sharaga nobody will appreciate it anyway. That's why I don’t bother) - Gnom Skull

1 answer 1

In your code, ExecuteReader is called, the result of which is then not used (since you try to get the real value from the line below through ExecuteScalar, called by the same command).

If only one line of processing is meant - delete ExecuteReader and the loop tied to it.

If you are processing multiple lines, read the norma value from the reader, inside the loop - and not by calling ExecuteScalar.

  • I removed using and made a string getting values ​​like this: norma = command.ExecuteReader (CommandBehavior.CloseConnection) .ToString (); but in the debugger it shows the value "System.Data.OleDb.OleDbDataReader". - Gnom Skull
  • @GnomSkull Well it should be - you got a reader, now read the values ​​from it one by one, via ReadInt32 - docs.microsoft.com/en-us/dotnet/framework/data/adonet/… - PashaPash