如何在TextBox中找到DataGridView中的字符串?

时间:2013-11-20 17:38:18

标签: c# string linq datagridview

嗨,我是Linq Queries的新手,此代码是从互联网上复制的

     object cells = from r in dataGridView1.Rows.Cast<DataGridViewRow>()where !r.IsNewRowArray.ConvertAll<DataGridViewCell, string>(r.Cells.Cast<DataGridViewCell>().ToArray, dgvc => dgvc.Value.ToString)where c.Contains(textBox1.Text)
                             select new  cell {
                            rowIndex = r.Index, 
                           columnIndex = Array.IndexOf(c, _textBox1.Text)};

并使用以下代码我在datagridview单元格中创建字符串。

 object cells = from r in dataGridView1.Rows.Cast<DataGridViewRow>()where !r.IsNewRowArray.ConvertAll<DataGridViewCell, string>(r.Cells.Cast<DataGridViewCell>().ToArray, dgvc => dgvc.Value.ToString)where c.Contains(_txt)
                             select new  cell {
                            rowIndex = r.Index, 
                           columnIndex = Array.IndexOf(c, _txt) 
 };

foreach (DataGridViewRow r in dataGridView1.Rows.Cast<DataGridViewRow>()) {
    foreach (DataGridViewCell c in r.Cells.Cast<DataGridViewCell>()) {
        if (!r.IsNewRow) {
            c.Style.BackColor = Color.White;
        }
    }
}

foreach (object c_loopVariable in cells) {
    c = c_loopVariable;
    DataGridView1.Rows(c.rowIndex).Cells(c.columnIndex).Style.BackColor = Color.Red;
}

并更改该单元格的颜色。

我想在datagridview中找到第一个空单元格(12列和8行),我的datagridview按列填充。当它进入第8行时,它会自动转到下一列,代码写在下面。其中_col和_row是全局声明的

        dataGridView1[_col, _row].Value = lvI.Text;
                _row = _row + 1;
                if (_row == 8)
                {
                    _row = 0;
                    _col = _col + 1;
                }

实际上我正在从listview填充datagridview。当我检查listview项时,datagridview基于列方式填充。当我取消选中它时会清除包含该文本的datagridview单元格。

我可以展示我的datagridview的图片以便更好地理解

enter image description here

取消选中后,

将会是这样的

enter image description here

1 个答案:

答案 0 :(得分:1)

如果您希望获取包含某些文字的所有单元格,请尝试使用此代码,旧查询会有一些依赖,而您错过了该部分。

var cells = dataGridView1.Rows.Cast<DataGridViewRow>()
             .SelectMany(row=>dataGridView1.Columns.Cast<DataGridViewColumn>()
                              .Select(col=>row.Cells[col.Name]))
             .Where(cell=>Convert.ToString(cell.Value).Contains(textBox1.Text));

cellsIEnumerable<DataGridViewCell>

然后,更改BackColor的代码可以是这样的:

foreach (var cell in cells) {
   cell.Style.BackColor = Color.Red;
}

请注意,您复制的所有代码都是无用的。

要获得第一个空单元格,您可以使用不同的条件执行相同的操作:

var firstEmptyCell = dataGridView1.Rows.Cast<DataGridViewRow>()
                    .SelectMany(row=>dataGridView1.Columns
                                    .Cast<DataGridViewColumn>()
                                    .Select(col=>row.Cells[col.Name]))
                    .OrderBy(cell=>cell.ColumnIndex)
                    .ThenBy(cell=>cell.RowIndex)
                    .FirstOrDefault(cell=>Convert.ToString(cell.Value) == "");
//The value of firstEmptyCell may be null if there is not any empty cell