2014-02-09 21 views
0

我有一個gridview,我有一個數據庫。在我的任務中,我將GridView綁定到數據庫,並且想要更改每列的寬度。Gridview的東西不對

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


如果我添加代碼到GridView1_RowDataBound,我得到一個錯誤:「指定參數超出參數名的有效值範圍:指數」。調試器的軌跡告訴我GridView1只有1列。爲什麼?在DB中我有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> 
+0

能否請您從ASPX頁面添加的GridView的代碼? –

回答

1

你需要檢查ROWTYPEGridView1_RowDataBound事件做它來代替。

試試這個

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

它的工作原理!謝謝!但是,怎樣才能在每個單元格上創建邊界呢?我可以把它放在所有網格或每一行上,但不是單元格 – mit

0

嘗試的GridView AutoGenerateColumns屬性設置爲True

AutoGenerateColumns="true" 

編輯:

如果你檢查是MSDN的DataAdapter.Fill方法;您正在使用的重載不存在。 請看這裏,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(); 
+0

我使用AutoGenerateColumns =「true」 – mit

+0

請參閱我編輯的答案。 – Rahul

+0

這是行不通的。 .. – mit