0

我尝试在绑定数据后更改gridview大小并重命名标题,但我收到错误“索引超出范围”,因为我的数据超过100px,如何解决?

                conn.Open();
                cmdString = "SQL";
                cmd = new SqlCommand(cmdString, conn);
                cmd.Parameters.AddWithValue("@courseID", CourseID);
                dtr = cmd.ExecuteReader();
                gvAssignment.DataSource = dtr;
                gvAssignment.Columns[7].ItemStyle.Width = Unit.Pixel(100);
                gvAssignment.DataBind();                  
                dtr.Close();
                conn.Close();

另一种方法没有错误,但大小不会更改为 100

    protected void gvAssignment_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        e.Row.Cells[7].Width = 100;
    }
4

2 回答 2

1

尝试先设置 DataBind,如下所示:

   gvAssignment.DataBind();  
   gvAssignment.Columns[7].ItemStyle.Width = Unit.Pixel(100); 

您也可以尝试在数据绑定后更新列宽。为了确保这一点,我们可以在 gridview 绑定事件中设置它

protected void Page_Load(object sender, EventArgs e)
{
    gvAssignment.DataBound += new EventHandler(gvAssignment_DataBound);
}

void gvAssignment_DataBound(object sender, EventArgs e)
{       
    gvAssignment.Columns[7].ItemStyle.Width = Unit.Pixel(100); 
}   
于 2012-12-07T23:20:29.200 回答
0

检查您的查询。“索引超出范围”可能指向列索引(如果您的查询中没有 8 列)

于 2012-12-07T23:17:38.823 回答