dmytro
dmytro

Reputation: 346

something wrong with gridview

I have a gridview and I have a DB. In my task I bind GridView to DB and want to change the width of every column.

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


If I add code into GridView1_RowDataBound, I get an error that: "Specified argument was out of the range of valid values. Parameter name: index". The trace of debugger shows me that GridView1 has only 1 column. Why? In DB I have 8 columns.

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

Regards




EDIT:

<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>

Upvotes: 0

Views: 67

Answers (2)

Krishnraj Rana
Krishnraj Rana

Reputation: 6656

You need to check RowType in the GridView1_RowDataBound event.

Try this

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;
        }
}

Upvotes: 1

Rahul
Rahul

Reputation: 77934

Try setting GridView AutoGenerateColumns property to True like

AutoGenerateColumns="true"

EDIT:

If you check is MSDN for DataAdapter.Fill Method; the overload you are using is not present. See here, http://msdn.microsoft.com/en-us/library/system.data.common.dataadapter.fill%28v=vs.80%29.aspx.

The overload which uses to fill a DataTable is DataAdapter.Fill (DataTable, IDataReader).

You should be doing it like this way instead by creating a DataSet

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

Upvotes: 0

Related Questions