简体   繁体   中英

why index out of range exception?

I am using this code to get the index of last row in gridview and then putting empty string in particular cell but throws error: Index out of range

protected void grdViewAdvances_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow) 
    {
        int RowIndex = grdViewAdvances.Rows.Count-1 ;

        grdViewAdvances.Rows[RowIndex].Cells[5].Text = "";
    }

The rows count would be changing for each row RowDataBound event. If you want to change the Text of last row column then let the bind process finish and assign the empty string after RowDataBound.

You probably need to do after the DataBind() method.

grdViewAdvances.DataSource = dt;
grdViewAdvances.DataBind();
grdViewAdvances.Rows[RowIndex].Cells[5].Text = "";

Edit

I just debugged the code and when on first time the code executed under if statement you have the Row Count is zero and subtracting one from it will give you row = -1 which is surely out of bound index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM