简体   繁体   中英

Autocomplete textbox in c#

I tried autocomplete text in c# and i tried this code,

try
{
   textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
   textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
   AutoCompleteStringCollection col = new AutoCompleteStringCollection();
   sqlconn.Open();
   string query = "select id from cmp_det where id =" + textBox1.Text;
   SqlCommand command = new SqlCommand(query, sqlconn);
   SqlDataReader sdr = command.ExecuteReader();
   while (sdr.Read())
   {
       col.Add(sdr["Column_Name"].ToString());    
   }
   sdr.Close();
   textBox1.AutoCompleteCustomSource = col;
   sqlconn.Close();
}
catch(Exception ex)
{
    Console.WriteLine("exception=="+ex);
}

when ) execute the code the following error appears:

exception==System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.

Try to replace your code:

SqlDataReader sdr = command.ExecuteReader();
while (sdr.Read())
{
   col.Add(sdr["Column_Name"].ToString());    
}
sdr.Close();

to this:

using(SqlDataReader sdr = command.ExecuteReader())
{
   while (sdr.Read())
   {
       col.Add(sdr.GetValue(0).ToString());    
   }
}

where 0 is the zero-based column ordinal of your query

Would enabling MARS fix this? Adding "MultipleActiveResultSets=True" to your connection string should resolve that type of error.

http://msdn.microsoft.com/en-us/library/h32h3abf(v=vs.80).aspx

This is due to a change in the default setting for MARs. It used to be on by default and we changed it to off by default post RC1. So just change your connection string to add it back (add MultipleActiveResultSets=True to connection string).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM