C# WPF datagrid найти и удалить строку - PullRequest
0 голосов
/ 02 марта 2020

Помоги мне. У меня есть 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);
            }
        }

1 Ответ

0 голосов
/ 02 марта 2020

Этот код должен работать:

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();

Не забудьте обновить sh сетку: datagrid.Items.Refresh()

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...