在我的表單中,我有一個文本框、后臺作業人員和一個資料網格視圖。使用文本框(TextChanged 屬性),我想使用后臺作業人員獲取資料,并在我鍵入時在資料網格視圖中填充匹配資料。
這是我嘗試過的。
private void txtSearchBox_TextChanged(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
backgroundWorker1.RunWorkerAsync();///Runs the background worker
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
con.Open();
MySqlDataAdapter da = new MySqlDataAdapter("select * from Games where Name like '%" txtSearchBox.Text "%'", con);
da.Fill(ds, "GameID");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" ex);
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
SimilarData.DataSource = ds.Tables["GameID"].DefaultView;
}
有了這個錯誤。ErrorSystem.InvalidOperationExceptoin:此后臺作業人員當前很忙,并且沒有同時運行多個任務。
我該怎么辦?
uj5u.com熱心網友回復:
如果您愿意接受比使用BackgroundWorker我建議的更簡單的方法,那就是async為事件創建一個處理程式,該處理程式textbox.TextChanged在等待快速輸入的“冷卻”期之前記錄擊鍵計數。如果等待此延遲之前和之后的計數相同,則表明輸入足夠穩定以執行查詢。

sqlite-net-pcl為了方便起見,我已經使用它來嘲笑它。DGV 系結到 aDataSource即 a BindingList<Game>。的OnLoad覆寫MainForm初始化DataGridView,然后是您正在使用的任何資料庫服務器。最后一件事是訂閱TextChanged事件,這是所有動作發生的地方。
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 initDGV()
{
dataGridView.DataSource = DataSource;
dataGridView.AllowUserToAddRows = false;
DataSource.Add(new Game { GameID = "Generate Columns" });
dataGridView
.Columns[nameof(Game.GameID)]
.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView
.Columns[nameof(Game.Created)]
.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
DataSource.Clear();
}
資料庫
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;
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/506401.html
上一篇:表配接器未更新到資料庫
