我的應用程序是關於這個的:我得到了sql數據庫裏面的產品,主要有Window.xaml
有DataGrid
和TextBox
。添加項目到DataGrid鍵入WPF,表現不佳?
應用程序非常簡單(下面解釋):
用戶應該尋找產品在TextBox
輸入產品代碼並按下Enter鍵,如果在數據庫中存在的產品與該代碼,它會被添加到DataGrid
!而這之後用戶可以決定他是否打算從DataGrid中刪除某些項目,或將全部打印出來等。
這裏是如何看,我做了油漆:)
點點繪製我的問題從這裏開始:
當我加入了從數據庫項目,我的DataGrid
它的工作在某種程度上慢,我的意思是不是很快,因爲它應該是,它真的可以感覺到有延時,當項目的點點正在被修改爲DataGrid
。
我以爲我做了所有事情,但可能我沒有,我想這肯定會有一些問題,或者我的代碼不好!
現在我會發布我的代碼,所以如果你們可以給我建議如何加快它或者建議我什麼我可以做得更好,請做到這一點,我真的apparaciate,因爲不知不覺我做錯了,也許我不是將數據綁定到一個DataGrid
因爲它應該還是別的什麼,但我不希望我的applicataion是緩慢的,特別是因爲它是非常簡單的應用程序..
這裏是我的代碼:
//I need to add new item from database to my DataGrid when user press Enter
private void txtCode_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
//Here I am making sure that I will not look for empty string in my database
if (!String.IsNullOrEmpty(txtCode.Text.Trim()))
{
//Here I am looking for product in my database with code that user entered
Article product = ArticlesController.GetProductByProductCode(txtCode.Text.Trim());
if (product!= null)
{
ProductTemporary tempProduct= new ProductTemporary();
tempProduct.ArticleCode = product.ArticleCode;
tempProduct.Price = product.Price;
tempProduct.Quantity = 1;
tempProduct.ArticleId = product.Id;
tempProduct.ArticleTitle = product.Title;
tempProduct.TotalAmount = (tempProduct.Quantity * tempProduct.Price);
//Here I'm adding item from database to Temp Table in case computer turns off, so when user log in back he can still find items he searched for before
var lastInserted = ProductsTempController.InsertNewTempProduct(tempProduct);
currentlyDataGridItems.Add(lastInserted);
dtgProductItems.ItemsSource = null;
dtgProductItems.ItemsSource = currentlyDataGridItems;
txtCode.Text = "";
txtCode.Focus();
}
else
{
MessageBox.Show("Product with next code:" + txtCode.Text + " does not exist.", "Search by product code", MessageBoxButton.OK, MessageBoxImage.Information);
txtCode.Text = "";
txtCode.Focus();
}
}
}
}
所以我想知道這段代碼有什麼問題,爲什麼我必須感覺到d當我添加項目到我的DataGrid時,我相信它需要時間來搜索數據庫中的產品,但acctualy我刪除所有除了5個產品,所以它應該工作真的很快,其實這是非常簡單的行動:
在數據庫中找不到項目,將其插入到一個臨時表,將其添加到DataGrid
但不知何故,它不能按預期工作速度快, 什麼的,非常感謝球員和歡呼聲!
關於性能的好問題,我希望有人會回答它如何改善,因爲我也很好奇! – 2017-03-02 21:05:42
'dtgProductItems.ItemsSource = null;'你爲什麼這樣做? – Emad
@Emad,因爲當用戶添加項目到一個數據網格我想立即向他展示它,像刷新數據網格..設置源爲空,然後再次添加它,但與內部的新項目.. –