c# - 使用 MS Access 数据库自动完成
问题描述
我想让我的 txtSearch 文本框在 Visual Studio 中自动完成。我搜索了很长时间,有些解释和教程,但大多数是关于 SQL 数据库的。我的应用程序中有一个 MS Access 数据库。
我想从我的数据库中的标题冒号(appData/Film)中提出自动完成建议
首先,文本框可以完成这项工作,还是富文本框是完成这项工作所必需的?我不希望您提供代码,但也许是解释或教程,您知道吗?
谢谢。哎呀。重要信息:我的应用程序基于 C#,并在 Visual Studio 中编码。
解决方案
试试这个方法。
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;
using System.Collections;
namespace WinAutoComplete
{
public partial class Form1 : Form
{
AutoCompleteStringCollection ProductList = new
AutoCompleteStringCollection();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//declare connection string
string cnString = @"Data Source=EXCEL-PC\SQLEXPRESS; Initial Catalog=NORTHWND;" +
"Trusted_Connection = True";
/*use following if you use standard security
string cnString = @"Data Source=(local);Initial
Catalog=northwind; Integrated Security=SSPI"; */
//declare Connection, command and other related objects
SqlConnection conGetData = new SqlConnection(cnString);
SqlCommand cmdGetData = new SqlCommand();
SqlDataReader drGetData;
try
{
//open connection
conGetData.Open();
//prepare connection object to get the data through
//reader and populate into dataset
cmdGetData.CommandType = CommandType.Text;
cmdGetData.Connection = conGetData;
cmdGetData.CommandText = "Select ProductName From Products";
//read data from command object
drGetData = cmdGetData.ExecuteReader();
if (drGetData.HasRows == true)
{
while (drGetData.Read())
ProductList.Add(drGetData["ProductName"].ToString());
}
else
MessageBox.Show("No data found in Products tables");
//close reader and connection
drGetData.Close();
conGetData.Close();
//set the default pattern to SuggestAppend
//comboBoxPattern.SelectedIndex = 1;
txtProductID.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txtProductID.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtProductID.AutoCompleteCustomSource = ProductList;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
//check if connection is still open then attempt to close it
if (conGetData.State == ConnectionState.Open)
{
conGetData.Close();
}
}
}
private void comboBoxPattern_SelectedIndexChanged(object sender, EventArgs e)
{
//switch (comboBoxPattern.Text)
//{
// case "Suggest":
// txtProductID.AutoCompleteMode = AutoCompleteMode.Suggest;
// break;
// case "Append":
// txtProductID.AutoCompleteMode = AutoCompleteMode.Append;
// break;
// case "SuggestAppend":
// txtProductID.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
// break;
//}
}
}
}
这绝对有效,正如您在下面的屏幕截图中看到的那样。
另外,如果有机会,请检查一下。