日期:2014-05-17  浏览次数:21155 次

c# combobox的模糊查询
数据是从数据库里得到的,
比方说当输入 河 字时,
combobox下拉菜单中会自动显示河南,河北等

建议下思路,谢谢了。

------解决方案--------------------
直接模糊查询数据不就得了,然后绑定到下拉列表
------解决方案--------------------
思路 
在Combobox的TextChanged里面处理 1楼说的 ,
------解决方案--------------------
我说下我的想法
数据:地名表里,有河南,河北字段的同时,增加一个便于索引的字段(河、河)
事件:KeyUp
C# code

     [PublishEvent("OnSearch")]
        public event EventHandler<DataEventArgs<string>> OnSearchEvent;
    private void txtSearch_KeyUp(object sender, KeyEventArgs e)
        {
            if (OnSearchEvent != null)
            {
                // Raise the event and notify the controller
                OnSearchEvent(this, new DataEventArgs<string>(txtSearch.Text));
            }  
        }

     // Search event from the view
        private void OnSearch(object sender, DataEventArgs<string> e)
      {
            // 1、更新数据集合代码
            // 2、更新界面
       }

------解决方案--------------------
this.comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
this.comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
------解决方案--------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient; 

namespace Combobox_实现数据库模糊查询动态绑定
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
static string SqlConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\C#项目文件\Database\MyPersonnel.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; 
SqlConnection conn = new SqlConnection(SqlConnectionString);
bool isover = false;
private void comboBox1_TextChanged(object sender, EventArgs e)
{
if (!isover)
{
string comboboxtext = this.comboBox1.Text.Trim();
string str = "SELECT 省份 FROM 省份信息 WHERE 省份 LIKE " + "'" + this.comboBox1.Text.Trim() + "%'";
SqlCommand comm = new SqlCommand(str, conn);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
SqlDataAdapter dataAdapter = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
List<string> shengfen = new List<string>();
foreach (DataRow row in ds.Tables[0].Rows)
{
foreach (DataColumn column in ds.Tables[0].Columns)
{
shengfen.Add(row[column].ToString());
}
}
int index=0;
for (int i = 0; i < shengfen.Count; i++)
{
if (shengfen[i] == comboboxtext)
{
index = i;
isover = true;
}
}
this.comboBox1.DataSource = shengfen;
this.comboBox1.SelectedIndex = index ;
this.comboBox1.DropDownStyle = ComboBoxStyle.DropDown;
}
else
{
}
}
}
}

可能还有些小问题,自己改下.
------解决方案--------------------