[英]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.