我在Winform应用程序中有一个文本框和列表框。当我在文本框中键入一个值(即字符串)时,我希望列表框显示数据表中的值,而当我从列表框中选择一个特定值时,它将显示在文本框中。

码:

private void txtIName_TextChanged(object sender, EventArgs e)
        {
            string constring = "Data Source=.;Initial Catalog=Test;User Id=sa;Password=admin@123";
            using (SqlConnection con = new SqlConnection(constring))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT distinct * FROM Item_Details", con))
                {
                    cmd.CommandType = CommandType.Text;
                    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                    {
                        using (dt = new DataTable())
                        {
                            sda.Fill(dt);
                            DataView dv = new DataView(dt);
                            dv.RowFilter = string.Format("IName Like '%{0}%'", txtIName.Text);
                            listBox1.Visible = true;
                            listBox1.DataSource = dv;

                        }
                    }
                }
            }
        }


但是我在列表框中得到了类似“ system.data.datarow”的输出。通过调试,我可以在dataview'dv'中看到我想要的行。我在这里想念什么?谢谢。

最佳答案

您无需每次TextChanged事件触发时都加载数据。在表单的Load事件中加载数据就足够了,然后在TextChanged中仅过滤数据即可。然后使用类似DoubleClick的事件,设置ListBox的文本:

private DataTable dataTable = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
    string constring = @"Data Source=.;Initial Catalog=Test;User Id=sa;Password=admin@123";
    using (SqlConnection con = new SqlConnection(constring))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter("SELECT distinct * FROM Item_Details", con))
        {
            sda.Fill(dataTable);
        }
    }
    this.listBox1.DataSource = new DataView(dataTable);
    this.listBox1.DisplayMember = "IName";
    this.listBox1.Visible = false;
}
private void txtIName_TextChanged(object sender, EventArgs e)
{
    var dv = (DataView)this.listBox1.DataSource;
    dv.RowFilter = string.Format("IName Like '%{0}%'", txtIName.Text);
    listBox1.Visible = true;
}
private void listBox1_DoubleClick(object sender, EventArgs e)
{
    var item = (DataRowView)listBox1.SelectedItem;
    if (item != null)
        this.txtIName.Text = item["IName"].ToString();
    else
        this.txtIName.Text = "";

    this.listBox1.Visible = false;
}


不要忘记将TextBoxForm1_LoadtxtIName_TextChanged处理程序附加到事件。

10-01 22:28
查看更多