I've been messing around with this and have yet to find a clean solution. At the moment, I have a asp:DataGrid control on the aspx page (I am open to changing this). When I click a button, I retrieve a DataSet from a database and use a DataTable from the DataSet to fill up my DataGrid.
If my asp:DataGrid is named "tableData" and my DataSet is named data the following implementation will fill my grid successfully:
protected void renderData(object sender, EventArgs e)
{
DataSet data = hc.getDataSet();
tableData.DataSource = data.Tab开发者_运维技巧les[0];
tableData.DataBind();
}
But my column widths are not as wide as desired. I would like to look at all the data in each column of data.Tables[0] and choose my tableData column's widths accordingly.
I have tried many ways of accomplishing this and failed but here are my two main ideas and the problems I've encountered:
Solution 1: Alter column width after the DataBind(). I would use some type of code along the lines of
tableData.Columns[i].ItemStyle.Width = longestField;
The problem with this solution is the DataBind() seems to not have taken place yet and I get some null pointer like exceptions. I could do it after, but how would I know when it is done? Even if there was some event like AfterDataBind I would prefer not to use it because if I would have to determine what table I was dealing with in that particular function.
Solution 2: Create my own databind method and use that instead
The problem with this solution is I can't seem to add rows to tableData myself (I would expect something like a tableData.NewRow() function but I can't seem to find one fitting my needs.
I have also tried using OnDataItemBound function, but I realized I have know idea how to relate the DataGridItemEventArgs e back to datagrid's column collection.
I would appreciate some insight. Thanks in advance guys.
Calculating column widths is a tricky business, and is prone to glitches. I would suggest setting fixed widths for columns with a limited amount of data, and let the grid use percentage widths for the other columns.
For example, let's say you have a list of addresses.
- Zip code should be less than 10 digits, so around 80px should be sufficient
- City is not as limited, but 200px will probably do the trick
- Street address could be really short or really long, so use a percentage width
If you're dead-set on calculating the column widths, take a look at this article:
http://www.syncfusion.com/FAQ/WindowsForms/FAQ_c44c.aspx#q877q
精彩评论