winforms 根据列和值在dataGridView中查找行

5m1hhzi4  于 2023-01-02  发布在  其他
关注(0)|答案(9)|浏览(200)

我有一个dataGridView,它有3列:SystemId、FirstName、LastName,它们是使用数据库信息绑定的。我想突出显示某个行,我将使用以下命令执行此操作:

dataGridView1.Rows[????].Selected = true;

然而,我不知道行ID,并且bindingsource在不断变化,因此第10行在一个示例中可能是“John Smith”,但在另一个示例中甚至不存在(我有一个过滤器,它根据用户输入的内容过滤掉源代码,因此键入“joh”将生成名/姓中包含“joh”的所有行,因此我的列表可以在一次单击中从50个名称变为3个)。
我想找到一种方法,根据SystemId和相应的编号选择行。我可以使用以下方法获取系统ID:

systemId = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["SystemId"].Value.ToString();

现在我只需要将它应用到行选择器中。类似于dataGridView1.Columns[“SystemId”].IndexOf(systemId},但这不起作用(也不存在这样的方法)。任何帮助都非常感谢。

qgzx9mmu

qgzx9mmu1#

这将为您提供值的gridview行索引:

String searchValue = "somestring";
int rowIndex = -1;
foreach(DataGridViewRow row in DataGridView1.Rows)
{
    if(row.Cells[1].Value.ToString().Equals(searchValue))
    {
        rowIndex = row.Index;
        break;
    }
}

或LINQ查询

int rowIndex = -1;

DataGridViewRow row = dgv.Rows
    .Cast<DataGridViewRow>()
    .Where(r => r.Cells["SystemId"].Value.ToString().Equals(searchValue))
    .First();

rowIndex = row.Index;

那么你可以:

dataGridView1.Rows[rowIndex].Selected = true;
vecaoik1

vecaoik12#

上面的答案只在AllowUserToAddRows被设置为false时有效。如果该属性被设置为true,那么当循环或Linq查询试图协商新行时,您将得到NullReferenceException。我修改了上面两个可接受的答案来处理AllowUserToAddRows = true
循环回答:

String searchValue = "somestring";
int rowIndex = -1;
foreach(DataGridViewRow row in DataGridView1.Rows)
{
    if (row.Cells["SystemId"].Value != null) // Need to check for null if new row is exposed
    {
        if(row.Cells["SystemId"].Value.ToString().Equals(searchValue))
        {
            rowIndex = row.Index;
            break;
        }
    }
}

LINQ回答:

int rowIndex = -1;

bool tempAllowUserToAddRows = dgv.AllowUserToAddRows;

dgv.AllowUserToAddRows = false; // Turn off or .Value below will throw null exception

    DataGridViewRow row = dgv.Rows
        .Cast<DataGridViewRow>()
        .Where(r => r.Cells["SystemId"].Value.ToString().Equals(searchValue))
        .First();

    rowIndex = row.Index;

dgv.AllowUserToAddRows = tempAllowUserToAddRows;
zfycwa2u

zfycwa2u3#

或者你可以这样用。这样可能更快。

int iFindNo = 14;
int j = dataGridView1.Rows.Count-1;
int iRowIndex = -1;
for (int i = 0; i < Convert.ToInt32(dataGridView1.Rows.Count/2) +1; i++)
{
    if (Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value) == iFindNo)
    {
        iRowIndex = i;
        break;
    }
    if (Convert.ToInt32(dataGridView1.Rows[j].Cells[0].Value) == iFindNo)
    {
        iRowIndex = j;
        break;
    }
    j--;
}
if (iRowIndex != -1)
    MessageBox.Show("Index is " + iRowIndex.ToString());
else
    MessageBox.Show("Index not found." );
7uhlpewt

7uhlpewt4#

试试这个:

string searchValue = textBox3.Text;
        int rowIndex = -1;

        dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        try
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (row.Cells["peseneli"].Value.ToString().Equals(searchValue))
                {
                    rowIndex = row.Index;
                    dataGridView1.CurrentCell = dataGridView1.Rows[rowIndex].Cells[0];
                    dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Selected = true;

                    break;
                }
            }
        }
        catch (Exception exc)
        {
            MessageBox.Show(exc.Message);
        }
brccelvz

brccelvz5#

如果您只想检查该项目是否存在:

IEnumerable<DataGridViewRow> rows = grdPdfs.Rows
            .Cast<DataGridViewRow>()
            .Where(r => r.Cells["SystemId"].Value.ToString().Equals(searchValue));
if (rows.Count() == 0) 
{
    // Not Found
} 
else 
{
    // Found
}
t8e9dugd

t8e9dugd6#

这是基于Gordon的上述回答--并不是所有的都是我的原创作品,我所做的是在我的静态实用程序类中添加一个更通用的方法。

public static int MatchingRowIndex(DataGridView dgv, string columnName, string searchValue)
        {
        int rowIndex = -1;
        bool tempAllowUserToAddRows = dgv.AllowUserToAddRows;

        dgv.AllowUserToAddRows = false; // Turn off or .Value below will throw null exception
        if (dgv.Rows.Count > 0 && dgv.Columns.Count > 0 && dgv.Columns[columnName] != null)
            {
            DataGridViewRow row = dgv.Rows
                .Cast<DataGridViewRow>()
                .FirstOrDefault(r => r.Cells[columnName].Value.ToString().Equals(searchValue));

            rowIndex = row.Index;
            }
        dgv.AllowUserToAddRows = tempAllowUserToAddRows;
        return rowIndex;
        }

然后以我想使用的任何形式调用该方法,传递DataGridView、列名和搜索值。为了简单起见,我将所有内容转换为字符串进行搜索,尽管添加重载来指定数据类型很容易。

private void UndeleteSectionInGrid(string sectionLetter)
        {
        int sectionRowIndex = UtilityMethods.MatchingRowIndex(dgvSections, "SectionLetter", sectionLetter);
        dgvSections.Rows[sectionRowIndex].Cells["DeleteSection"].Value = false;
        }
mrzz3bfm

mrzz3bfm7#

使用WPF的用户

for (int i = 0; i < dataGridName.Items.Count; i++)
{
      string cellValue= ((DataRowView)dataGridName.Items[i]).Row["columnName"].ToString();                
      if (cellValue.Equals("Search_string")) // check the search_string is present in the row of ColumnName
      {
         object item = dataGridName.Items[i];
         dataGridName.SelectedItem = item; // selecting the row of dataGridName
         dataGridName.ScrollIntoView(item);                    
         break;
      }
}

如果您希望在此之后获取选定的行项目,则以下代码片段很有用

DataRowView drv = dataGridName.SelectedItem as DataRowView;
DataRow dr = drv.Row;
string item1= Convert.ToString(dr.ItemArray[0]);// get the first column value from selected row 
string item2= Convert.ToString(dr.ItemArray[1]);// get the second column value from selected row
tvokkenx

tvokkenx8#

string text = "param";

var rows = dataGridViewlist.Rows.OfType<DataGridViewRow>()
                                 .Select(x => new { Value = x.Cells[6].Value.ToString(), Index = x.Index }).ToList();

var index= rows.Where(w => w.Value == text).Select(s => s.Index).FirstOrDefault();
oxcyiej7

oxcyiej79#

您可以尝试:

string DT = string.Empty;
try
 {
   DT = $"{dataGridView1.SelectedRows[0].Cells[1].Value}-{dataGridView1.SelectedRows[0].Cells[2].Value}-{dataGridView1.SelectedRows[0].Cells[3].Value}-{dataGridView1.SelectedRows[0].Cells[4].Value}";
 }
catch { }

try
 {
   dataGridView1.Rows.Cast<DataGridViewRow>().Where(x => $"{x.Cells[1].Value}-{x.Cells[2].Value}-{x.Cells[3].Value}-{x.Cells[4].Value}" == DT).ToList()[0].Selected = true;
 }
catch (Exception ex) { }

相关问题