将字符串值与任何单元格中的datagridview第0行进行比较

时间:2015-08-18 17:44:00

标签: c# visual-studio datagridview

当我搜索这个问题时,我找不到任何东西,因为我真的不知道怎么说出来。

我有一个从excel文件中获取值的dataGridView。这工作正常,但我想将第0行中的所有值与字符串值进行比较。

这是我的代码

string mat = "test";
if(mat == dataGridView1[0,0].Value.ToString())
        {
            tst.Text = dataGridView1[1,0].Value.ToString();
        }

仅适用于第一个条目中的单元格。我需要扫描所有值。我认为它会是这样的:

string mat = "test";
int x = ???;
if(mat == dataGridView1[0,x].Value.ToString())
        {
            tst.Text = dataGridView1[1,x].Value.ToString();
        }

这让我感到疯狂,因为我知道这是一件非常简单的事情。否则,我将不得不复制和粘贴x等于1,2,3等,因为这个工作表有很多值。

任何建议都将不胜感激。

2 个答案:

答案 0 :(得分:1)

你可以在循环中进行验证

string mat = "test";
for(int i=0;i<dataGridView1.Rows[0].Cells.Count;i++){
        if(dataGridView1[0,i].Value != null && mat == dataGridView1[0,i].Value.ToString())
        {
            tst.Text = dataGridView1[1,i].Value.ToString();
        }
}

我强烈建议您阅读此article

答案 1 :(得分:1)

if(dataGridView1 != null)
{
    foreach (DataGridViewCell cell in dataGridView1.Rows[0].Cells)
    {
        if (cell.Value != null && cell.Value.Equals("test"))
        {
            tst.Text = cell.Value;
        }
    }
}
相关问题