【问题标题】:Adding Stuff into a Gridview with a For-Loop使用 For 循环将东西添加到 Gridview 中
【发布时间】:2015-11-13 06:35:27
【问题描述】:

我正在尝试使用 For-Loop 将一些数据放入我的 Datagridview

但问题是,如果我的计数器无缘无故地为 2,我的循环就会跳出,我不知道为什么

这是我的代码:

var row = new DataGridViewRow();
//image directory
DirectoryInfo dir = new DirectoryInfo(@"C:\Users\Daniel\Pictures");

//getting all files from the Directory
foreach(FileInfo file in dir.GetFiles())
{

    try
    {
         this.img16x16.Images.Add(Image.FromFile(file.FullName));

    }catch
    {
         Console.WriteLine("This is not an image file");
    }
}
for (int j = 0; j <= this.img16x16.Images.Count; j++)
{

    dataGridView1.Rows[j].Cells[0].Value = img16x16.Images[j].ToString();
    img16x16.ImageSize = new Size(16, 16);
    dataGridView1.Rows[j].Cells[1].Value = img16x16.Images[j];
    dataGridView1.Rows.Add(row);

感谢您的帮助

编辑:我找到了解决方案,我只需要输入这些 2:

var row = new DataGridViewRow();
dataGridView1.Rows.Add(row);

在for循环内我的代码前面

【问题讨论】:

  • 一方面,您的循环最后会出现异常。
  • 哦,是的,谢谢我没注意到

标签: c# for-loop datagridview


【解决方案1】:

看起来您已经混淆了行变量和数据网格的行。

for(int j = 0;  j < this.img16x16.Images.Count; j++)
{
    row = new DataGridViewRow();
    //Add first cell and its data to the variable "row"
    //Size changes
    //Add second cell and its data to the variable "row"

    //Add "row" to the grid:
    dataGridView1.Rows.Add(row);
}

在您的版本中,您直接写入网格而没有提及它的大小,我猜它是一两行大的其他设置,并且您尝试在其范围之外写入。

【讨论】:

  • 感谢您的帮助,我找到了解决方案并将其编辑到我的主题中:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-23
  • 1970-01-01
  • 2022-10-09
  • 2022-06-11
  • 1970-01-01
  • 2020-10-22
  • 1970-01-01
相关资源
最近更新 更多