2013-04-11 118 views
0

研究員程序員,我試圖在Gridview的最後一列(已綁定到某個SQL數據庫)中獲取值,然後用生成的超鏈接替換該單元格的內容,具體取決於該單元格的值可能是。 我迄今爲止代碼:在Gridview中獲取單元格的值

protected void Page_Load(object sender, EventArgs e) 
{ 
    /* Load the Required Data */ 
    StrCommand="SELECT "+ Request.QueryString["Cols"] + " FROM " + Request.QueryString["Category"]; 
    SqlConnection myConnection = new SqlConnection(); 
    myConnection.ConnectionString = "Data Source=localhost;" + "Initial Catalog=Categories; Integrated Security=SSPI"; 
    SqlCommand myCommand = new SqlCommand(StrCommand, myConnection); 
    myConnection.Open(); 
    SqlDataReader DataReader1 = myCommand.ExecuteReader(); 
    ProductList.DataSource = DataReader1; 
    ProductList.DataBind(); 
    myConnection.Close(); 

    /* Post-binding modifications are now applied to the Grid View */ 

    /* Generate the column containing the add-to-cart buttons */ 
    for (int j = 0; j < ProductList.Rows.Count-1; j++) 
    { 
     int id_holder = int.Parse(ProductList.Rows[j].Cells[ProductList.Columns.Count-1].Text); 

    } 


} 

不幸的是,該代碼失敗,我得到這個錯誤:

Specified argument was out of the range of valid values. Parameter name: index 

任何想法表示讚賞,
利奧

+0

你處理了什麼事件? – 2013-04-11 03:55:46

+1

這裏你寫這個代碼???是你寫它在rowdatabound – 2013-04-11 03:56:03

+0

哪一個失敗:行[j]或單元[ProductList.Columns.Count-1]? – 2013-04-11 04:48:55

回答

0

我找到了答案,當GridView.AutoGenerateColumns屬性設置爲「True」時,ProductList.Columns.Count未更新,並將其值保留爲「0」。另一種方法是使用:ProductList.Rows [0] .Cells.Count。否則,我們可以將AutoGenerateColumns設置爲false並構建我們自己的列模板。

乾杯。

2

如果故障是索引列的範圍內,將for語句更改爲:

for (int j = 0; j < ProductList.Rows.Count - 1; j++) 

由於數組基於零而count不是。

+3

這是錯誤的,條件是'j V4Vendetta 2013-04-11 04:45:22

相關問題