【发布时间】:2016-07-12 09:54:36
【问题描述】:
我对创建列表视图项有非常简单的逻辑。我将 dataGridView 中的所有 col 标题名称存储到 ColNamesForm1 数组中,然后仅比较最后 5 个字符是否与 (num) 或 (cat)强>字符串。对于这两个选项,我使用存储在静态类 OtherFunctions 中的 Populate 函数将不同的图片附加到列表视图 lvMoveFrom 中。
但是我的代码有问题,因为在最后一次迭代之后,它从最后一列附加图像 - 如果第一列是 (num),最后一列是 (cat),则列表视图中的图像都是相同的 - 来自 cat图片。
我该如何解决这个问题?我想知道为每一列创建新的 ImageList 对象,但我不知道如何动态地做到这一点,例如使用循环索引 i。
请您帮忙解决我的问题。
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < ColNamesForm1.Length; i++)
{
if (ColNamesForm1[i].ToString().Substring(0, 4).ToUpper() != "COL_" && Regex.IsMatch(ColNamesForm1[i].ToString().Substring(4, 1), @"^\d+$") == false)
{
if (ColNamesForm1[i].ToString().Substring(ColNamesForm1[i].ToString().Length - 5) == "(num)")
{
OtherFunctions.Populate(lvMoveFrom, ColNamesForm1[i].ToString(), @"C:\pictures\num.png");
}
else
{
OtherFunctions.Populate(lvMoveFrom, ColNamesForm1[i].ToString(), @"C:\pictures\cat.png");
}
}
}
}
public static void Populate(ListView lv, string itemName, string pathToPicture)
{
ImageList img = new ImageList();
img.ImageSize = new Size(30, 30);
img.Images.Add(Image.FromFile(pathToPicture));
lv.SmallImageList = img;
lv.Items.Add(itemName, 0);
}
【问题讨论】:
-
ColNamesForm1[i].ToString().Substring(ColNamesForm1[i].ToString().Length - 5) == "(num)"等于ColNamesForm1[i].ToString().EndsWith("(num)") -
ColNamesForm1是什么类型 -
可以,因为每次调用
lv.SmallImageList = img;时都使用相同的ListView,所以最后一组图像将是lv使用的图像。你应该给每个Item一张图片