网格视图有问题



我有一个网格视图,我有一个数据库。在我的任务中,我将 GridView 绑定到数据库,并希望更改每列的宽度。

dataAdapter = new SqlDataAdapter("SELECT *  FROM Turs", sqlcn);
dt = new DataTable("Turs");
dataAdapter.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();


如果我将代码添加到GridView1_RowDataBound中,则会收到错误:"指定的参数超出了有效值的范围。参数名称:索引"。调试器的跟踪显示 GridView1 只有 1 列。为什么?在数据库中,我有 8 列。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        e.Row.Cells[0].Width = 100;
        e.Row.Cells[1].Width = 150;
    }

问候




编辑:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
        BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" Font-Size="Medium"
        ShowHeaderWhenEmpty="True" AutoGenerateColumns="True" 
        onrowdatabound="GridView1_RowDataBound">
        <EditRowStyle BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" />
        <HeaderStyle Font-Bold="True" Font-Size="Larger" ForeColor="Blue" />
        <RowStyle BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" />
    </asp:GridView>
您需要

GridView1_RowDataBound事件中检查 RowType

试试这个

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[0].Width = 100;
            e.Row.Cells[1].Width = 150;
        }
}

尝试将 GridView AutoGenerateColumns属性设置为True

AutoGenerateColumns="true"

编辑:

如果选中是 MSDN for DataAdapter.Fill Method;则不存在您正在使用的重载。http://msdn.microsoft.com/en-us/library/system.data.common.dataadapter.fill%28v=vs.80%29.aspx,请看这里。

用于填充数据表的重载DataAdapter.Fill (DataTable, IDataReader)

您应该通过创建DataSet来以这种方式执行此操作

DataSet ds = new DataSet();
dataAdapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();

最新更新