[英]ListBox.DataSource doesn't show data on the list
伙计们,我有一个积分列表积分= new List(); ,我正在尝试从列表中删除一些数据。 我使用一个列表框来查看它是否有效。 这是我的代码:
points.Add(new PointF(50, 100));
points.Add(new PointF(50, 100));
points.Add(new PointF(200, 300));
points.Add(new PointF(100, 200 ));
points.Add(new PointF(50, 100));
points.Add(new PointF(100, 200));
points.Add(new PointF(200, 300));
points.Add(new PointF(100, 200));
points.Add(new PointF(200, 300));
listBox1.DataSource = points;
float[] sumofxandy = new float[points.Count()];
for (int x = 0; x < points.Count(); x++)
{
sumofxandy[x] = points.ElementAt(x).X + points.ElementAt(x).Y;
}
//code that removes data from list starts from here
float[] difference = new float[points.Count()]; //there is something wrong with this and I don't know what. It has no error but it doesn't make my list to be shown in the listbox.
for (int i = 0; i <= points.Count(); i++)
{
for (int j = 1; j <= points.Count(); j++)
{
difference[j] = sumofxandy[i] - sumofxandy[j];
if (difference[i] == 0)
{
points.RemoveAt(j);
MessageBox.Show("removed");
}
}
} // ends here
listBox2.DataSource = points;
当我删除从列表中删除数据的代码时,列表中的元素将显示在列表框中。 伙计们
可能是您在if(difference[i] == 0)
中使用了错误的变量吗?
当使用您的解决方案时,我在行points.RemoveAt(j);
收到ArgumentOutOfRangeException points.RemoveAt(j);
difference[j] = sumofxandy[i] - sumofxandy[j];
if (difference[i] == 0)
{
points.RemoveAt(j);
MessageBox.Show("removed");
}
当行if(difference[i] == 0)
更改为:
if(difference[j] == 0)
然后代码成功执行,listbox2中有3个项目。
编辑:
正如@wdosanjos所提到的,您应该使用<
而不是<=
循环,因为您是从零开始计数,而不是从1开始。最后一个元素实际上位于Count-1位置,因为列表的索引为零。
编辑:
当我将循环更改为:(注意将<=
更改为<
,它不会引发异常。)
for (int i = 0; i < points.Count(); i++)
{
for (int j = 1; j < points.Count(); j++)
{
difference[j] = sumofxandy[i] - sumofxandy[j];
if (difference[i] == 0)
{
points.RemoveAt(j);
MessageBox.Show("removed");
}
}
} // ends here
这将返回两个元素。
尝试如下更改for
循环(从<=
到<
)。 我认为您正在获取隐藏的IndexOutOfBoundsException
。
for (int i = 0; i < points.Count(); i++)
{
for (int j = 1; j < points.Count(); j++)
请注意,您正在修改的列表完全相同。 这可能很容易删除所有要点。 您最好为应该删除的点创建一个新列表:
//code that removes data from list starts from here
List<PointF> pointsToRemove = new List<PointF>();
float[] difference = new float[points.Count()];
for (int i = 0; i <= points.Count(); i++)
{
for (int j = 1; j <= points.Count(); j++)
{
difference[j] = sumofxandy[i] - sumofxandy[j];
if (difference[i] != 0)
{
pointsToRemove.Add(points[j]);
MessageBox.Show("removed");
}
}
}
listBox2.DataSource = points.Except(pointsToRemove).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.