2011-12-28 91 views
0

我有以下的代碼:數據網格設置列寬編程

protected void Page_Load(object sender, EventArgs e) 
    { 
     var src1 = Page.DataContext.ExtranetTypes; 
     var res1 = from row in src1 select row; 

     var src2 = Page.DataContext.ExtranetDocuments; 
     var res2 = from row in src2 select row; 

     var query = from r1 in res1 
        join r2 in res2 on r1.ID equals r2.FileTypeID 
        select new { r2.PublicationDate, Title = r2.Title, Type = r1.Title }; 

     DocumentGrid.DataSource = query; 
     DocumentGrid.DataBind(); 
    } 

我想設定的列的寬度,但我不能爲每列設置的寬度,因爲查詢有尚未執行。

DocumentGrid.Columns[1].ControlStyle.Width 

給出了一個錯誤,因爲當查詢excecuted列進行計算,並且它在最新的時刻執行可能的,因爲後期綁定。有什麼辦法可以設置這些列的寬度嗎?

+0

看看這裏http://odetocode.com/articles/218.aspx – 2011-12-28 14:46:58

+1

使用BoundField列而不是自動生成的列。 – adatapost 2011-12-28 15:00:31

回答

1

當數據源有一些東西要顯示時,會生成一個datagrid或gridview。如果沒有顯示,那麼網格不會在頁面上呈現。但是如果你想在沒有數據的情況下顯示網格,那麼添加一個骨架數據表或列表來渲染網格,然後你的代碼就可以工作。此外,如果你貼網格的HTML,這將是一個馬麗娟幫助

-2

使用

DocumentGrid.DataSource = query.ToList(); 

那麼你可以設置寬度編程。這是因爲query.ToList()提交數據並使它們可由DocumentGrid.DataSource屬性讀取。

+0

它不會解決問題,asd他要求增加寬度 – 2011-12-28 16:17:43

+0

query.ToList()命令後,他可以以編程方式設置寬度。 – Flaick 2012-01-10 09:46:24

0

我使用了BoundFields,因爲我的問題中有一條評論的建議。

結果:

<asp:GridView ID="DocumentGrid" runat="server" AutoGenerateColumns="False"> 
    <Columns> 
     <asp:BoundField HeaderText="Publication Date" DataField="PublicationDate" ItemStyle-Width="120px"/> 
     <asp:BoundField HeaderText="Title" DataField="Title" ItemStyle-Width="400px"/> 
     <asp:BoundField HeaderText="Type" DataField="Type" ItemStyle-Width="100px"/> 
    </Columns> 
</asp:GridView> 

只要確保自動生成列設置爲false,否則你會得到額外列。