获取Gridview中单元格的值

本文关键字:单元格 Gridview 获取 | 更新日期: 2023-09-27 18:08:29

程序员,我试图获得Gridview(已绑定到一些SQL数据库)的最后一列的值,然后用生成的超链接替换该单元格的内容,这取决于该单元格的值可能是什么。我的代码到目前为止:

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

任何想法都很感谢,
狮子座

获取Gridview中单元格的值

如果失败是index out of range,则将for语句更改为:

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

我找到了答案,当GridView。AutoGenerateColumns属性设置为"True",ProductList.Columns.Count不更新,将其值保留为"0"。另一种方法是使用:ProductList.Rows[0]. cells . count。否则,我们可以将autogeneratecolcolumns设置为false并构建我们自己的列模板。

欢呼。