2015-10-15 210 views
0

我在使用我的代碼時遇到了一些麻煩。 我試圖爲每種情況展示不同的圖片。 但代碼似乎有缺陷,我很新的C#和ASP.net,所以我很容易迷路。 下面是崩潰的代碼的所述部分:RowIndex超出範圍

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未被識別(不顯示在智能感知上)。 如果你能看到我出錯的地方,爲什麼這會崩潰,如何解決它我會永遠感激。

+1

您可以註釋掉該行'GridViewRow行= GridView1.Rows [e.RowIndex]'你有一定要採取,除了用行索引賦值之外,你不會在'OnRowDataBound'中的任何地方使用實例變量'row'。 – Prabhat

+0

非常感謝!我想我會看到它出錯的地方。 –

回答

1

你不需要轉換

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

相反,你可以直接使用它作爲

GridViewRow row = e.Row;