在DataGridView中搜索字符串

本文关键字:字符串 搜索 DataGridView | 更新日期: 2023-09-27 18:26:51

我正在通过以下代码将CSV加载到DataGridView中

        string rowValue;
        string[] cellValue;
        if(File.Exists(textBoxFilePath.Text.ToString().Trim()))
        {
        StreamReader streamReader = new StreamReader(textBoxFilePath.Text.ToString().Trim());
        rowValue = streamReader.ReadLine();
        cellValue = rowValue.Split(',');
        for (int i = 0; i <= 4 - 1; i++)
        {
            DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
            column.Name = cellValue[i];
            column.HeaderText = cellValue[i];
            dataGridView1.Columns.Add(column);
        }
        // Reading content
        while (streamReader.Peek() != -1)
        {
            rowValue = streamReader.ReadLine();
            cellValue = rowValue.Split(',');
            DateTime dt = new DateTime();
            dt = DateTime.Now;
            String month = dt.Month.ToString();
            String day = dt.Day.ToString();
            if (dt.Month < 10)
            {
                month = "0" + dt.Month;
            }
            if (dt.Day < 10)
            {
                day = "0" + dt.Day;
            }
            String stringDate = dt.Year.ToString() + "/" + month + "/" + day;
            Console.WriteLine(dt.ToShortDateString());
            Console.WriteLine(stringDate);
            if (cellValue[2].CompareTo(stringDate) == 0)
            {
                dataGridView1.Rows.Add(cellValue);                    
            }
        }
        streamReader.Close();
        dataGridView1.Sort(this.dataGridView1.Columns["User-Name"], ListSortDirection.Ascending);
        }
        else 
        {
            MessageBox.Show("No File is Selected");
        }

我想搜索用户名。这是第2列。

在DataGridView中搜索字符串

您可以按照以下模式访问DataGridView中任意单元格的value

dataGridView.Rows[rowIndex].Cells[columnIndex].Value

您正在查找User-Name列的特定值吗?如果是这样,你可以这样处理:

string searchedText = "some name";
var matchedRows = this.dataGridView1.Rows
    .Cast<DataGridViewRow>()
    .Select(r => r.Cells["User-Name"].Value)
    .Where(v => v != null && v.ToString() == searchedText)
    .ToList();

matchedRows列表将包含与搜索字符串匹配的所有行。请注意,您需要为.Cast.Where方法包含using System.Linq;命名空间。