【问题标题】:Check if gridview column on each row has the same values检查每行上的gridview列是否具有相同的值
【发布时间】:2016-08-29 13:25:00
【问题描述】:

如何检查每行上的网格视图列是否具有相同的值。

以下代码将应用的条件是什么。

代码

int y = 0;
foreach (GridViewRow row in gridreq.Rows)
{
    string catid = row.Cells[2].Text;
    if (//condition)
    {
        y = y + 1;

    }
}

if (y == 0)
{

//code

}
else
{
 //code
}

【问题讨论】:

    标签: c# asp.net gridview


    【解决方案1】:

    除了foreach 中的foreach 之外,没有可行的方法来检查一行的值与所有 其他行的值。一些解决方法:

    也许您可以检查第一个值?

    int y = 0;
    var checkItem = gridreq.Rows[0].Cells[2].Text;
    foreach (GridViewRow row in gridreq.Rows)
    {
        string catid = row.Cells[2].Text;
        if (catid == checkItem)    //or use String.compare here
        {
            y = y + 1;
    
        }
    }
    

    另一种方法是对照之前行的值检查该值。

    int y = 0;
    string catidCheck = "";
    foreach (GridViewRow row in gridreq.Rows)
    {
        string catid = row.Cells[2].Text;
        if (catid == catidCheck)    //or use String.compare here
        {
            y = y + 1;
        }
        catidCheck = catid;
    }
    

    【讨论】:

      【解决方案2】:

      使用Linq distinct 应该可以做到这一点:

      int y = gridreq.Rows.Select((row) => row.Cells[2].Text).Distinct().Count()
      

      那我猜你以后的情况应该是if (y == 1)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-03
        • 2021-03-24
        相关资源
        最近更新 更多