SqlDataReader Runtime Error

im trying to get the specialization identifier from the Specializationtbl table using C # MSVS 2008, and the table includes SpecializationName and SpecializationID next to some other lines, and my question is related to some error “No data to present”, the command goes like below:

SqlCommand READSpecID = new SqlCommand("SELECT * FROM Specializationtbl WHERE SpecializationName='" + comboBox1.Text + "'" , DBcnction);
DBcnction.Open();

SqlDataReader ReadSpecID_ = READSpecID.ExecuteReader();
ReadSpecID_.Read();
int SpecID_ = Convert.ToInt16(ReadSpecID_["SpecID"].ToString());

DBcnction.Close();

I also tried to select “SpecID” instead of all the lines, but can not seem to have sealed the request correctly and kept getting the “Missing data” error, any idea where I am making the error?

+3
source share
3 answers

1) Try to open DBcnction before assigning the value READSPecID

DBcnction.Open();
SqlCommand READSpecID = new SqlCommand("SELECT * FROM Specializationtbl WHERE     SpecializationName='" + comboBox1.Text + "'" , DBcnction);

2) Run the command in SSMS:

 SELECT * FROM Specializationtbl WHERE SpecializationName ='yourvalue'

and see if any results are returned.

3) , comboBox1.Text

4) comboBox1.Text( ), , SQL Injection: http://en.wikipedia.org/wiki/SQL_injection

+1

:

  • SQL- SQL.
  • ExecuteScalar, .
  • using.
 string retVal;        
 using (var conn = new SqlConnection(SomeConnectionString))
 using (var cmd = conn.CreateCommand())
 {
   cmd.CommandText = "SELECT SpecID FROM Specializationtbl WHERE SpecializationName= @Name";
   cmd.Parameters.AddWithValue("@Name", comboBox1.Text);
   conn.Open();
   retVal = cmd.ExecuteScalar().ToString();
}
int specID = int.Parse(retVal);

:

 using (var conn = new SqlConnection(SomeConnectionString))
 using (var cmd = conn.CreateCommand())
 {
   cmd.CommandText = "SELECT SpecID, Value2 FROM Specializationtbl WHERE SpecializationName= @Name";
   cmd.Parameters.AddWithValue("@Name", comboBox1.Text);
   conn.Open();
   var dr = cmd.ExecuteReader();
   while (dr.Read())
   {
      Customer c = new Customer { 
             ID = dr["SpecID"].ToString(),
             Value = dr["Value2"].ToString(),
       };
   }
}
+1

You must first check if there are any lines. I suspect the query returns null strings.

if (ReadSpecID_.HasRows) {ReadSpecID_.Read (); }

+1
source

All Articles