在DataGridView中搜索字符串

时间:2012-03-05 18:05:12

标签: c# search datagrid csv datagridview

我正在通过以下代码将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栏。

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

您是否在寻找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列表将包含与您的搜索字符串匹配的所有行。请注意,您需要为using System.Linq;.Cast方法添加.Where命名空间。