protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
initDGV();
initSQL();
textBox.TextChanged += onTextBoxTextChanged;
}
BindingList<Game> DataSource = new BindingList<Game>();
// Comparing the awaited count to the total count so that
// the DGV isn't visually updated until all queries have run.
int _queryCount = 0;
TextBox.TextChanged事件处理程序(异步)
private async void onTextBoxTextChanged(object sender, EventArgs e)
{
if(string.IsNullOrWhiteSpace(textBox.Text))
{
return;
}
_queryCount++;
var queryCountB4 = _queryCount;
List<Game> recordset = null;
var captureText = textBox.Text;
// Settling time for rapid typing to cease.
await Task.Delay(TimeSpan.FromMilliseconds(250));
// If keypresses occur in rapid succession, only
// respond to the latest one after a settling timeout.
if (_queryCount.Equals(queryCountB4))
{
await Task.Run(() =>
{
using (var cnx = new SQLiteConnection(ConnectionString))
{
var sql = $"SELECT * FROM games WHERE GameID LIKE '{captureText}%'";
recordset = cnx.Query<Game>(sql);
}
});
DataSource.Clear();
foreach (var game in recordset)
{
DataSource.Add(game);
}
}
else Debug.WriteLine("Waiting for all pending queries to complete");
}
private void initSQL()
{
// For testing, start from scratch every time
if (File.Exists(ConnectionString)) File.Delete(ConnectionString);
using (var cnx = new SQLiteConnection(ConnectionString))
{
cnx.CreateTable<Game>();
cnx.Insert(new Game { GameID = "Awe" });
cnx.Insert(new Game { GameID = "Abilities" });
cnx.Insert(new Game { GameID = "Abscond" });
cnx.Insert(new Game { GameID = "Absolve" });
cnx.Insert(new Game { GameID = "Absolute" });
}
}
游戏
[Table("games")]
class Game
{
[PrimaryKey, Browsable(false)]
public string Guid { get; set; } = System.Guid.NewGuid().ToString().ToUpper();
public string GameID { get; set; }
private DateTime _created = DateTime.Now.Date;
public string Created
{
get => _created.ToShortDateString();
set
{
if(DateTime.TryParse(value, out DateTime dt))
{
_created = dt.Date;
}
}
}
}
1条答案
按热度按时间polkgigr1#
如果您愿意接受比使用
BackgroundWorker
更简单的方法,我建议您为textbox.TextChanged
事件创建一个async
处理程序,记录在等待快速输入的“冷却”期之前的击键计数。如果计数在等待此延迟之前和之后相同,则表明输入足够稳定,可以执行查询。为了方便起见,我用
sqlite-net-pcl
模拟了这个过程。DGV绑定到一个DataSource
,它是一个BindingList<Game>
。OnLoad
覆盖MainForm
初始化DataGridView
,然后初始化你正在使用的任何数据库服务器。最后一件事是订阅TextChanged
事件,这是所有动作发生的地方。TextBox.TextChanged
事件处理程序(异步)数据网格视图
数据库
游戏