RealityDysfunction
RealityDysfunction

Reputation: 2639

Get Value of Cell in Gridview

Fellow programmers, I am trying to obtain values in the last column of Gridview (which has been bound to some SQL database) and then replace the contents of that cell with a generated hyperlink depending on what the value of that cell may be. My code so far:

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); 

    }


}

Unfortunately, this code fails, and I get this error:

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

Any ideas are appreciated,
Leo

Upvotes: 0

Views: 198

Answers (2)

RealityDysfunction
RealityDysfunction

Reputation: 2639

I have found the answer, when GridView.AutoGenerateColumns property is set to "True" the ProductList.Columns.Count is not updated, leaving it at value of "0." The alternative is to use: ProductList.Rows[0].Cells.Count. Otherwise we can set AutoGenerateColumns to false and build our own Column Template.

Cheers.

Upvotes: 0

devilfish17
devilfish17

Reputation: 337

If the failure is index out of range, change the for statement to:

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

As arrays are zero based and count is not.

Upvotes: 2

Related Questions