RowIndex 超出范围

RowIndex out of range

我的代码有问题。 我试图为每种情况展示不同的图片。 但是代码似乎有缺陷,我对 C# 和 ASP.net 很陌生,所以我很容易迷路。 这是崩溃的代码部分:

    protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        GridViewRow row = GridView1.Rows[e.RowIndex];
        string Class = (e.Row.FindControl("txtClass") as TextBox).Text;
        HtmlControl htmctrl = e.Row.FindControl("imgid") as HtmlControl;
        switch (Class)
        {
            case "A1":
                {
                    string Logo = @"C:\Users\Rudra\documents\visual studio 2010\Projects\MvcApplication1\MvcApplication1\Images\Box_Blue.png";
                    htmctrl.Attributes.Add("src", Logo);
                    break;
                }
            case "A2":
                {
                    string Logo = @"C:\Users\Rudra\documents\visual studio 2010\Projects\MvcApplication1\MvcApplication1\Images\Box_Green.png";
                    htmctrl.Attributes.Add("src", Logo);
                    break;
                }
            case "A3":
                {
                    string Logo = @"C:\Users\Rudra\documents\visual studio 2010\Projects\MvcApplication1\MvcApplication1\Images\Box_Red.png";
                    htmctrl.Attributes.Add("src", Logo);
                    break;
                }
            default:
                {
                    string Logo = @"C:\Users\Rudra\documents\visual studio 2010\Projects\MvcApplication1\MvcApplication1\Images\not-found.png";
                    htmctrl.Attributes.Add("src", Logo);
                    break;
                }
        }
    }

崩溃发生在第一行GridViewRow row = GridView1.Rows[e.RowIndex];RowIndex 未被识别(未显示在智能感知上)。 如果您能看到我哪里出错了,为什么会崩溃以及如何修复它,我将永远感激不已。

您无需转换

GridViewRow row = GridView1.Rows[e.RowIndex];

相反,您可以直接将其用作

GridViewRow row = e.Row;