我在c#中尝试了autocomplete
文字,我尝试了这段代码,
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)执行代码时出现以下错误:
exception==System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.
答案 0 :(得分:1)
尝试替换您的代码:
SqlDataReader sdr = command.ExecuteReader();
while (sdr.Read())
{
col.Add(sdr["Column_Name"].ToString());
}
sdr.Close();
到此:
using(SqlDataReader sdr = command.ExecuteReader())
{
while (sdr.Read())
{
col.Add(sdr.GetValue(0).ToString());
}
}
其中0是查询的从零开始的列序号
答案 1 :(得分:0)
启用MARS会解决此问题吗?将"MultipleActiveResultSets=True"
添加到连接字符串应解决该类型的错误。
http://msdn.microsoft.com/en-us/library/h32h3abf(v=vs.80).aspx
答案 2 :(得分:0)
这是因为MAR的默认设置发生了变化。 它曾经默认打开,我们默认将其更改为关闭后RC1。因此,只需更改连接字符串即可将其添加回来(将MultipleActiveResultSets = True添加到连接字符串中)。