Click here to Skip to main content
15,893,381 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
This code works after selecting an item in the combo box --but when I change the selected item-- I get an error.

Can you help me fix this code?

C#
string query = "select SupplierNo from Supplier WHERE SupplierName = '" + cbosupplier.SelectedItem.ToString() + "'";
              SqlCommand cmd = new SqlCommand(query, cn);
              cmd.CommandText = query;

              
              SqlDataReader rdr = cmd.ExecuteReader();

              while (rdr.Read())
              {
                  
                  txtsupplierno.Text = rdr["SupplierNo"].ToString();
              }
Posted
Comments
Sergey Alexandrovich Kryukov 27-Jun-12 20:58pm    
How? You don't show your event handler on selection changed.
You string concatenation '+' with the query text is just unacceptable -- use parametrized query.
--SA
DamithSL 27-Jun-12 23:25pm    
What is the error you get?
wolfsor 28-Jun-12 4:24am    
"There is already an open DataReader associated with this Command which must be closed first." I added "rdr.close();" to close it

you can check cbosupplier.SelectedItem value before search on database.

if there is empty or default value, you can avoid before search
C#
var supplier = cbosupplier.SelectedItem.ToString();
if(!string.IsNotNullOrEmpty(supplier)|| supplier != "please Select supplier")
{
  // search on Database
}


And you need to use Parameters[^]

and Also check for null before call ToString

C#
if (rdr["SupplierNo"] != DBNull.Value)
{
    ltlAdditional.Text = rdr["SupplierNo"].ToString();
}


One more thing:

If you need to Append Text use

C#
ltlAdditional.Text += rdr["SupplierNo"].ToString();
 
Share this answer
 
v4
Comments
AshishChaudha 27-Jun-12 23:51pm    
Good answer.my 5!
Vani Kulkarni 28-Jun-12 5:38am    
My 5 too!
at the bottom, I added:


C#
rdr.close();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900