简体   繁体   中英

Error Specified argument was out of the range of valid values. Parameter name: index in DataGridview Row Data Bound

I got an error of

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index

Source Error:

if (e.Row.RowType == DataControlRowType.DataRow)
{
    LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[2];
    string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "Select$" + e.Row.RowIndex);
    e.Row.Style["cursor"] = "hand";

my code

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("itemid", typeof(string)),
                new DataColumn("itemdesc", typeof(string)),
                new DataColumn("itemtype",typeof(string)) });
        dt.Rows.Add("FG001", "Red Velvet Cake (8'' round)","Dry Goods");
        dt.Rows.Add("FG002", "Voilet Velvet Cake (8'' round)", "Dry Goods");
        GridView1.DataSource = dt;
        GridView1.DataBind();  
    }
}

protected void OnDataBound(object sender, EventArgs e)
{
    GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
    for (int i = 0; i < GridView1.Columns.Count; i++)
    {
        TableHeaderCell cell = new TableHeaderCell();
        TextBox txtSearch = new TextBox();
        txtSearch.Attributes["placeholder"] = GridView1.Columns[i].HeaderText;
        txtSearch.CssClass = "search_textbox";

        cell.Controls.Add(txtSearch);
        row.Controls.Add(cell);
    }

    GridView1.HeaderRow.Parent.Controls.AddAt(1, row);
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (!IsPostBack)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
            string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "Select$" + e.Row.RowIndex);
            e.Row.Style["cursor"] = "hand";
            e.Row.Attributes["onclick"] = _jsSingle;
        } 
    }
}

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    GridViewRow selectedRow = GridView1.SelectedRow;
    hiddenitemid.Value = selectedRow.Cells[0].Text;
}

the error pointing

LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];

Either you have rows without any cells, or you have a cell with less than three controls.

To prevent the code from crashing, just check if you have enough items:

if (e.Row.Cells.Count > 0)
{
    TableCell cell = e.Row.Cells[0];
    if (cell.Controls.Count > 2)
    {
        LinkButton _singleClickButton = (LinkButton)cell.Controls[2];
        string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "Select$" + e.Row.RowIndex);
        e.Row.Style["cursor"] = "hand";
    }
}

The reason behind this error is there are no cells available in your gridview when your code is executing.

You are adding columns to the gridview and binding it to datatable in page_load that too in "if(!this.IsPostBack)" block. So columns will be added to the gridview only when the page loads first time. And when gridview event is fired and page is posted back the page_load is executed again but no columns added and no databinding done to the gridview.

After that gridview's event handler gets executed and it does not find any cells in the row (coz there are no columns in the grid) so it does not go inside "if (e.Row.Cells.Count > 0)" block. And if you try to access cells using Cells[0] it throws Exception.

The solution to this problem is to define column structure of grid view in the HTML and bind gridview to data source in the code behind.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="itemdesc" HeaderText="Item Description" ReadOnly="True" />
        <asp:BoundField DataField="itemtype" HeaderText="Item Type" ReadOnly="True" />
    </Columns>
</asp:GridView>

Or you write code of adding columns to gridview in the InitialzeComponents() method which is executed every time page loads.

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