Button Click事件的GridView更新崩溃

时间:2015-06-26 18:28:45

标签: c# asp.net gridview

在ButtonClick事件上填充gridview后面对的数组超出了gridview的异常。当从页面加载触发时,相同的源工作正常。无法在stackoverflow上找到类似的帖子。请指教。感谢。

代码:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    e.Row.Cells[0].Attributes["width"] = "30px";
    e.Row.Cells[1].Attributes["width"] = "40px";   -> CRASHES AT INDEX 1
    e.Row.Cells[2].Attributes["width"] = "40px";
    e.Row.Cells[3].Attributes["width"] = "50px";
    e.Row.Cells[4].Attributes["width"] = "50px";
    e.Row.Cells[5].Attributes["width"] = "100px";
    e.Row.Cells[5].HorizontalAlign = HorizontalAlign.Left;
}

<asp:GridView ID="GridView1" runat="server" CellPadding="4"
    ForeColor="Black" GridLines="Horizontal" Width="100%" ShowHeader="true" 
    EmptyDataText="No Records found.!" 
    RowStyle-Wrap="true" AllowPaging="true" PageSize="5"
    OnPageIndexChanging="gridView_PageIndexChanging"
    OnRowDataBound="GridView1_RowDataBound"         
    style="table-layout:fixed; word-wrap:break-word; margin-left: 0px;" >

1 个答案:

答案 0 :(得分:1)

您应该检查它是什么类型的行。我正在检查DataRow,但您可能只想为Header执行此操作。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Cells[0].Attributes["width"] = "30px";
        e.Row.Cells[1].Attributes["width"] = "40px";   -> CRASHES AT INDEX 1
        e.Row.Cells[2].Attributes["width"] = "40px";
        e.Row.Cells[3].Attributes["width"] = "50px";
        e.Row.Cells[4].Attributes["width"] = "50px";
        e.Row.Cells[5].Attributes["width"] = "100px";
        e.Row.Cells[5].HorizontalAlign = HorizontalAlign.Left;
    }
}