簡體   English   中英

C# WPF datagrid 查找和刪除行

[英]C# WPF datagrid find and delete row

幫我。 我有用於查找的textbox和用於查找的datagrid 我想在第一列中搜索數據與從textbox導入的數據相似的行並將其刪除。 我該怎么辦?

感謝您的幫助。 幸運的新月

我的代碼我嘗試:

for (int i = 0; i < datagrid.Items.Count; i++)
{
            TextBlock cellValue = datagrid.Columns[i].GetCellContent(datagrid.Items[0]) as TextBlock;
            string cellValue2 = cellValue.Text;
            if (cellValue2 == textbox.text) // check the search_string is present in the row of ColumnName
            {
                datagrid.Items.RemoveAt(i);
            }
        }

此代碼應該工作:

for (int i = datagrid.Items.Count-1; i >= 0; i--)
{
    var cellValue = datagrid.Columns[0].GetCellContent(datagrid.Items[i]) as TextBlock;
    string cellValue2 = cellValue.Text;
    if (cellValue2 == textbox.Text) // check the search_string is present in the row of ColumnName
    {
        //For the case you set an ItemsSource:
        (datagrid.ItemsSource as IList)?.Remove(datagrid.Items[i]);
        //For the case you add Items directly:
        try
        {
            datagrid.Items.Remove(datagrid.Items[i]);
        }
        catch (Exception)
        {
        }
    }
}
datagrid.Items.Refresh();

不要忘記刷新網格: datagrid.Items.Refresh()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM