我有一个.Net 4 Windows窗体应用程序,它使用一个Microsoft Access数据库,其中一个表有三列CityCode,Name和Country。
我想要做的是拥有一个显示“名称”和“国家/地区”的自动填充功能,但选中后,“CityCode”值会显示在文本框中。此外,如果用户输入城市代码,例如LAX,因为他们输入L,它将列出所有代码或名称以L开头的城市。
可以这样做吗?
目前我有以下访问数据库(但似乎有点慢!)
textBoxCity.AutoCompleteCustomSource = CityList();
public static AutoCompleteStringCollection CityList()
{
string connectionStringLD = string.Empty;
connectionStringLD = @"Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\CityList.mdb";
string SQL = "SELECT CityCode from CityTable";
OdbcConnection conn = new OdbcConnection(connectionStringLD);
OdbcCommand cmd = new OdbcCommand(SQL);
cmd.Connection = conn;
conn.Open();
OdbcDataReader reader = cmd.ExecuteReader();
AutoCompleteStringCollection theCityList = new AutoCompleteStringCollection();
while (reader.Read())
{
theCityList.Add(reader.GetValue(0).ToString());
}
return theCityList;
}
答案 0 :(得分:0)
您可以使用Like '%' Query in your Sql Statement
根据您的输入返回城市名称。
答案 1 :(得分:0)
我不确定你用
得到了什么我想要做的是拥有一个显示“名称”和“国家/地区”的自动填充功能,但在选中时,“CityCode”值会显示在文本框中。
但我可以回答你问题的自动完成部分。
为此,您需要将数据导入DataTable;你可以将数据库中的数据读入表中,但正确的方法是使用OleDbConnection,OleDbDataAdapter和OleDbCommandBuilder - msdn有例子。
现在它在DataTable中,将它绑定到ComboBox:
var query =
from row in mytable.AsEnumerable()
select new { citycode = row.Field<string>("CityCode") } // put whatever you want in the anonymous type
mycombobox.DisplayMember = "citycode"
mycombobox.ValueMember = "citycode" // this one can be a different member name
mycombobox.DataSource = query.toList(); // the datasource should be set last
现在您可以将组合框行为设置为自动完成:
如果您希望允许用户键入他们想要的内容并仅建议您的数据表值作为选项,那么您应该只设置AutoCompleteCustomSource而不用担心与DataSource的实际数据绑定。
这有点麻烦;由于城市不是每秒几次打开国际机场,您可能更愿意将所有机场代码转储到List中,您也可以将数据绑定到。