C#在组合框中搜索 [英] C# search in combobox

查看:58
本文介绍了C#在组合框中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将记录从我的数据库加载到组合框..有时加载所有记录但有时它显示错误..我不知道组合框事件是问题还是我的方法..请帮助新手..



错误信息:



im trying to load record from my db to a combobox.. sometimes loads all record but sometimes it shows an error.. i dont know if the combobox event is the problem or my method.. pls help newbie..

error message:

InvalidArgument=Value of '0' is not valid for 'index'.
Parameter name: index





我尝试过:



//我的方法



What I have tried:

//my method

void loadSubject(ComboBox cbo)
        {
            try
            {
                SqlConnection con = new SqlConnection(cs.getConnectionString());
                con.Open();
                DataTable dt = new DataTable();
                string query = "SELECT subjectcode,description FROM tblsubject WHERE description LIKE '%' + @1 + '%' ORDER BY description ASC";
                SqlCommand cmd = new SqlCommand(query, con);
                cmd.Parameters.AddWithValue("@1",cbosubject.Text);
                SqlDataReader dr = cmd.ExecuteReader();
                dt.Load(dr);
                cbo.DisplayMember = "description";
                cbo.ValueMember = "subjectcode";
                cbo.DataSource = dt;
            }
            catch (Exception)
            {
                publicFunctions.mBox(3, "error occured");
            }
        }





//我的组合框活动



//my combobox event

private void cbosubject_TextChanged(object sender, EventArgs e)
        {
            loadSubject(cbosubject);
        }

推荐答案

我怀疑问题出在文本更改事件中。您正在更改该事件中的Combobox项目源,这将导致文本更改,触发事件或导致其他一些错误。

如果您需要按照设置的方式使用功能,我建议您使用文本框来键入/触发更改的文本,并使用单独的列表框来保存列表,从而形成loadsubject调用。请注意,通过在文本的每个更改中查询数据库,您可能会发现性能损失......
I suspect the issue lies in the text changed event. You are changing the Combobox's itemsource in that event which will then cause a change in the text, triggering the event or causing some other error.
If you need the functionality the way you have set it up, I recommend you use a text box for the typing / triggering of text changed and a separate list box that holds the list form the loadsubject call. Note that you'll probably find a performance hit by querying the database on every change in text...


这篇关于C#在组合框中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆