根据条件获取GridView的具体记录

我试图从网格视图中获取最后两个值,不包括零价格的项目。


网格视图数据


ITEMCODE    ITEMNAME       PRICE

001         Ice Tea         5.0000

002         Super Delux     12.0000

003         Meditern Veg    0.0000

004         Super  L        0.0000

005         Super  L        33.0000

所以在这种情况下所需的输出是


Value1:005

Value2:002

代码


protected void Button1_Click(object sender, EventArgs e)

{

    int count = 0;

    foreach (GridViewRow row in this.GridView1.Rows)

    {

        if ((row.Cells[2].Text != "0"))

        {

            count = (count + 1);

        }


    }


    Int32 Value1 = (count - 1);

    Int32 Value2 = (count - 2);

    lblValue1.Text = GridView1.Rows[Value1].Cells[0].Text;

    lblValue2.Text = GridView1.Rows[Value2].Cells[0].Text;

}

我厌倦的代码没有返回所需的输出。


慕村9548890
浏览 145回答 1
1回答

拉丁的传说

这应该有效:protected void Button1_Click(object sender, EventArgs e){&nbsp; &nbsp; List<DataGridViewRow> CountRows = new List<DataGridViewRow>();&nbsp; &nbsp; for (int i = this.GridView1.Rows.Count-1; CountRows.Count < 2 || i >= 0; i--)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if ((double)this.GridView1.Rows[i].Cells[2].Value != 0)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CountRows.Add(this.GridView1.Rows[i]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; if(CountRows.Count >= 1)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; lblValue1.Text = "Value1:" + CountRows[0].Cells[0].Text;&nbsp; &nbsp; }&nbsp; &nbsp; if(CountRows.Count == 2)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; lblValue2.Text = "Value2:" + CountRows[1].Cells[0].Text;&nbsp; &nbsp; }}我所做的是使用常规 for 循环从结束到开始计数,当找到 2 行或到达开始时停止。找到的行被放在一个列表中以保存它们。我在最后使用了额外的 if,以免在找到少于 2 行时(不是在您的示例中)使索引超出范围异常。请随意编辑。希望能帮助到你!
打开App,查看更多内容
随时随地看视频慕课网APP