简体   繁体   中英

C# WPF datagrid find and delete row

Help me. i have textbox for find and datagrid for find . I want to search in the first column the rows with data similar to the data imported from the textbox and delete it. How do I do?

Thank for help. lucky new month

My code i try:

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

This code should work:

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

Don't forget to refresh the grid: datagrid.Items.Refresh()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM