从C#中的列表框中删除项目

时间:2016-11-04 03:08:19

标签: c# listbox indexoutofrangeexception

您好我试图点击按钮删除和项目,但我一直在

  

' IndexOutOfRange'异常。

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    clientNum = clientList.Items.Count;
    for (int i = 0; i < clientNum; i++)
    {
        nameSeletion[i] = clientList.Items[i].ToString();
    }

    if (dateSeletion[clientList.SelectedIndex] != null)
    {
        dateCalender.SelectionStart = todayDate[clientList.SelectedIndex];
        Check();
    }
    else
    {
        nameLbl.Text = nameSeletion[clientList.SelectedIndex];
        dateText.Text = "";
    }
}

if (dateSeletion[clientList.SelectedIndex] != null)是我遇到错误的地方。

按钮代码是

private void button1_Click(object sender, EventArgs e)
{
    clientList.Items.Remove(clientList.Items[clientList.SelectedIndex]);
}

dateSelection在保存按钮和初始化

中定义
private void SaveBtn_Click(object sender, EventArgs e)
    {
        //save the list array for names
        for (int i = 0; i < clientNum; i++)
        {
            nameSeletion[i] = clientList.Items[i].ToString();
        }

        dateSeletion[clientList.SelectedIndex] = dateCalender.SelectionStart.Date.ToShortDateString() +
            " " + clientTime.Value.ToShortTimeString();
        todayDate[clientList.SelectedIndex] = dateCalender.SelectionStart;
        dateCalender.BoldedDates = todayDate;
        Check();

    }

public ClientForm()
    {
        InitializeComponent();
        clientNum = clientList.Items.Count;
        todayDate = new DateTime[clientNum];
        dateSeletion = new string[clientNum];
        nameSeletion = new string[clientNum];
        clientTime.CustomFormat = "hh:mm tt";

        //initialize the list array for names
        for (int i = 0; i < clientNum; i++)
        {
            nameSeletion[i] = clientList.Items[i].ToString();
        }

    }

1 个答案:

答案 0 :(得分:0)

试试这个

clientList.RemoveAt(clientList.SelectedIndex);