[英]Is it possible to size a gridview's columns if the gridview is dynamically bound?
我正在使用C#和ASP.NET,在ASP頁上有以下內容:
<div id="divGrid" style='position:absolute; width:920px; height:400px; overflow:auto'>
<asp:GridView ID="GridView_Reports" runat="server" AutoGenerateColumns="true"
Width="1300px"
onselectedindexchanged="GridView_Reports_SelectedIndexChanged"
onrowdatabound="GridView_Reports_RowDataBound"
CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<EditRowStyle BackColor="#999999" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
</asp:GridView>
</div>
在后面的代碼中,我有以下代碼片段:
//Now open the View and bind it to the GridView
string SelectView = "SELECT * FROM " + MySQLView + "";
SqlConnection con = new SqlConnection(str2);
SqlCommand SelectCmd = new SqlCommand(SelectView, con);
SqlDataAdapter SelectAdapter = new SqlDataAdapter(SelectCmd);
//Fill the dataset
DataSet RunReport = new DataSet();
SelectAdapter.Fill(RunReport);
GridView_Reports.DataSource = RunReport;
GridView_Reports.DataBind();
因此,如您所見,數據集是動態創建的。 我這樣做是因為有幾種可能的報告,並且我想使其盡可能通用。
從我的谷歌搜索看來,當GridView動態完成時,它實際上沒有列。 這樣,以下代碼行將始終返回0:
int columnscount = GridView_Reports.Columns.Count;
我一生無法解決如何遍歷所有列並動態設置其寬度的問題。 硬編碼這不是一個選擇。 整個表單是由表驅動的,因此添加新報表就像向表中添加信息一樣容易,而且我不會對20多個報表的列信息進行硬編碼。 Rows.Count工作正常,必須有一種方法可以某種方式遍歷各列並設置其寬度? 即使我可以將它們的寬度全部設置為相同的大小,也可以,但是我只需要指定該大小即可!
我尚未對此進行測試,但可能值得嘗試。 另外,您是否可以不調用單獨的方法來執行此數據綁定操作。
在DataGrid中:
OnItemDataBound="dgMyGrid_ItemBound"
背后的代碼:
protected void dgMyGrid_ItemBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item)
{
e.Item.Cells["MyCol"].CssClass = "MyCssClass";
}
}
編輯:
抱歉,無法正確閱讀您的問題。 您使用的是DataGridView而不是DataGrid。 嘗試看一下: 將列表綁定到datagridview時修復列寬
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.