日期:2014-05-17  浏览次数:21102 次

dataGridView1遍历的问题
c#的dataGridView1如何遍历,并且返回行号?

目前是不要绑定DataSet。

我这样遍历出现异常:

if (this.dataGridView1.Rows.Count > 0)
{
    for (int j = 0; j < this.dataGridView1.Rows.Count; j++)     
    {
        if ((this.dataGridView1.Rows[j].Cells[0].Value.ToString()=="XX") &&
                                        (this.dataGridView1.Rows[j].Cells[1].Value.ToString()=="YY"))
        {
           indx = j;
           return;
        }
    }
}

------解决方案--------------------
(this.dataGridView1.Rows[j].Cells[0].Value.ToString()=="XX") &&
                                        (this.dataGridView1.Rows[j].Cells[1].Value.ToString()=="YY")

Value会不会为null??
------解决方案--------------------
先看明白是什么错误, Value如果为null,ToString会报错,还要确定Cells[0]和Cells[1]是否存在
------解决方案--------------------
不知道你报的什么错 无法给出答案
------解决方案--------------------
引用:
我改成以下代码,则不会报错:
if (this.dataGridView1.Rows.Count > 0)
{
    for (int j = 0; j < this.dataGridView1.Rows.Count; j++)     
    {
        if ((this.dataGridView1.Rows[j].Cells[0].ToString()=="XX") &&
                                        (this.dataGridView1.Rows[j].Cells[1].ToString()=="YY"))
        {
           indx = j;
           return;
        }
    }


但是有问题,dataGridView1里面没有数据也会遍历一下;有符合条件的数据又不能返回行号!


你把一个CELL类型tostring 和一个