我有一个listBox1,其中收集了项目。
以button1单击开始的timer1。
还有progressBar1
这是完整的代码。
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Interval = 500;
progressBar1.Maximum = listBox1.Items.Count;
}
private void timer1_Tick(object sender, EventArgs e)
{
x.Send("<iq type='set' to='" + textBox6.Text + "@conference.jabber.com'>" +
"<query xmlns='http://jabber.org/protocol/muc#admin'>" +
"<item jid='" + listBox1.Items[0].ToString() +
"@nimbuzz.com' affiliation='member'/></query></iq>");
listBox1.Items.RemoveAt(0);
progressBar1.Value += 1;
groupBox4.Text = listBox1.Items.Count.ToString();
}
上面的代码运行良好但是当listBox1中剩下0项时,progressBar1停止出现错误
System.ArgumentOutOfRangeException未处理消息: InvalidArgument =&#39; 0&#39;的值对于&#39; index&#39;无效。参数名称:index
答案 0 :(得分:1)
如何进行简单检查
if (listBox1.Items.Count > 0)
{
listBox1.Items.RemoveAt(0);
}
答案 1 :(得分:1)
试试这个
private void timer1_Tick(object sender, EventArgs e)
{
if(listBox1.Items.Count > 0) {
x.Send("<iq type='set' to='" + textBox6.Text + "@conference.jabber.com'><query xmlns='http://jabber.org/protocol/muc#admin'><item jid='" + listBox1.Items[0].ToString() + "@nimbuzz.com' affiliation='member'/></query></iq>");
listBox1.Items.RemoveAt(0);
progressBar1.Value += 1;
groupBox4.Text = listBox1.Items.Count.ToString();
}
}
答案 2 :(得分:0)
我的答案与已发布的内容基本相同,但格式有所改善。最好使用string.Format()
来帮助提高代码的可读性。
private void timer1_Tick(object sender, EventArgs e)
{
if (listBox1.Items.Count > 0)
{
x.Send(string.Format(
"<iq type='set' to='{0}@conference.jabber.com'><query xmlns='http://jabber.org/protocol/muc#admin'><item jid='{1}@nimbuzz.com' affiliation='member'/></query></iq>",
textBox6.Text,
listBox1.Items[0].ToString()));
listBox1.Items.RemoveAt(0);
progressBar1.Value += 1;
groupBox4.Text = listBox1.Items.Count.ToString();
}
}