gpt4 book ai didi

c# - 在紧凑的框架中动态增长和收缩 DataGrid?

转载 作者:太空宇宙 更新时间:2023-11-03 20:25:12 26 4
gpt4 key购买 nike

我在 Compact Framework 中有一个 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);
}

关于c# - 在紧凑的框架中动态增长和收缩 DataGrid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10992547/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com