1
我在Compact Framework中有一個DataGrid我需要填充數以萬計的記錄,這證明是一個問題,因爲當我嘗試時,內存不足。在緊湊框架中動態增長和縮小DataGrid?
有沒有辦法動態地只顯示和加載用戶正在查看的行,而不是一次性將所有行轉儲到網格中?
我在Compact Framework中有一個DataGrid我需要填充數以萬計的記錄,這證明是一個問題,因爲當我嘗試時,內存不足。在緊湊框架中動態增長和縮小DataGrid?
有沒有辦法動態地只顯示和加載用戶正在查看的行,而不是一次性將所有行轉儲到網格中?
下面的代碼將自動調整其數據源爲數組的數據網格的列寬。
public static void AutosizeColumnsWithArray(DataGrid grid, PaintEventArgs e)
{
Font dataFont = grid.Font;
Font headerFont = GetHeaderFont(dataFont);
IList list = null;
if (grid.DataSource is IList)
{
list = (IList) grid.DataSource;
}
else if (grid.DataSource is IListSource)
{
list = ((IListSource) grid.DataSource).GetList();
}
if (list == null || list.Count < 0)
{
return;
}
if (grid.TableStyles.Count == 0)
{
return;
}
var pdc = TypeDescriptor.GetProperties(list[0]);
var dataGridTableStyle = new DataGridTableStyle();
dataGridTableStyle.MappingName = GetMappingName(list);
int totalWidth = 0;
for (int i = 0; i < pdc.Count; i++)
{
var columnName = pdc[i].Name;
bool validColumn = grid.TableStyles[0].GridColumnStyles.Contains(columnName);
if (!validColumn)
{
continue;
}
var gridColumnStyle = grid.TableStyles[0].GridColumnStyles[columnName];
var indexToEdit = grid.TableStyles[0].GridColumnStyles.IndexOf(gridColumnStyle);
var headerText = grid.TableStyles[0].GridColumnStyles[columnName].HeaderText;
var maxSize = e.Graphics.MeasureString(headerText, headerFont);
int maxLength = headerText.Length;
int rowCount = 0;
const int maxRowsToCompare = 200;
foreach (object o in list)
{
if (rowCount == maxRowsToCompare)
{
break;
}
object result = pdc[i].GetValue(o);
string value = result == null ? string.Empty : result.ToString().Trim();
if (ValueCannotBeLongest(value, maxLength))
{
rowCount++;
continue;
}
SizeF size = e.Graphics.MeasureString(value, dataFont);
if (size.Width > maxSize.Width)
{
maxSize = size;
maxLength = value.Length;
}
rowCount++;
}
var newWidth = (int) (maxSize.Width + 5);
grid.TableStyles[0].GridColumnStyles[indexToEdit].Width = newWidth;
totalWidth += newWidth;
}
}
private static bool ValueCannotBeLongest(string value, int maxLength)
{
return (value.Length == 0) || (value.Length + 3 < maxLength);
}
private static string GetMappingName(IList list)
{
string result;
if (list is ITypedList)
{
result = ((ITypedList) list).GetListName(null);
}
else
{
result = list.GetType().Name;
}
return result;
}
private static Font GetHeaderFont(Font dataFont)
{
string FontName = dataFont.Name;
float FontSize = dataFont.Size;
return new Font(FontName, FontSize, FontStyle.Bold);
}
這可能會回答你的問題:http://stackoverflow.com/questions/6120299/out-of-memory-netcf-windows-mobile-5 – yms