我刚才写的是与用户写入一个文本框的信息查询SQL数据库我的第一个程序。 这是使用Windows窗体C#。 我的目标是有这种类似的地方结果显示为一个用户类型(类似于谷歌的预测搜索功能)在我们的ERP软件的搜索功能。
我所挣扎的是减少的查询数到数据库。 现在我有这么不执行查询,直到用户类型为至少3个字符,否则过多的结果将被返回。
private void SearchField_TextChanged(object sender, EventArgs e)
{
string search = SearchField.Text;
if (search.Length >= 3)
{
dataGridView1.DataSource = sql.ExecuteQuery(Query(search));
}
}
直到用户已经停止打字,而没有进入这么多毫秒的性格我想补充的是查询延迟。 我一直在寻找的定时器类,但与我找到正确实现它的例子中挣扎。 基本上,我想改变我的代码是类似以下内容:
private void SearchField_TextChanged(object sender, EventArgs e)
{
string search = SearchField.Text;
if (search.Length >= 3 && aTimer.Time > 500) //500 is milliseconds
{
dataGridView1.DataSource = sql.ExecuteQuery(Query(search));
}
aTimer.Reset();
}
如果使用Timer类,我不知道如何正确地执行它。 如果有一个更好的解决方案,我是持开放的态度为好。
你想要做的是安排查询在未来的某个时刻发生,同时能够重置或撤销悬而未决查询作为用户类型。 下面是一个例子:
using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
class Form1 : Form
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
Timer queryTimer;
TextBox SearchField;
public Form1()
{
Controls.Add((SearchField = new TextBox { Location = new Point(10, 10) }));
SearchField.TextChanged += new EventHandler(SearchField_TextChanged);
}
void SearchField_TextChanged(object sender, EventArgs e)
{
if (SearchField.Text.Length < 3)
RevokeQueryTimer();
else
RestartQueryTimer();
}
void RevokeQueryTimer()
{
if (queryTimer != null)
{
queryTimer.Stop();
queryTimer.Tick -= queryTimer_Tick;
queryTimer = null;
}
}
void RestartQueryTimer()
{
// Start or reset a pending query
if (queryTimer == null)
{
queryTimer = new Timer { Enabled = true, Interval = 500 };
queryTimer.Tick += queryTimer_Tick;
}
else
{
queryTimer.Stop();
queryTimer.Start();
}
}
void queryTimer_Tick(object sender, EventArgs e)
{
// Stop the timer so it doesn't fire again unless rescheduled
RevokeQueryTimer();
// Perform the query
Trace.WriteLine(String.Format("Performing query on text \"{0}\"", SearchField.Text));
}
}