jae33
jae33

Reputation: 85

c# argument out of range was unhandled due to the SelectedIndex

'Argument out of range was unhandled' error occur when button is clicked due to no number or no such index number of client connected is selected. Error show to this code:

workerSocket = (Socket)m_workerSocketList[comboBox1.SelectedIndex];

i want to give a message box say 'Please select a correct number'. what should be coded to handle this error?

here is the code:

void indmsgbtn_Click(object sender, EventArgs e)
{
    string msg = richtxtindmsg.Text;
    msg = "Private Admin Message: " + msg + "\n";
    byte[] byData = System.Text.Encoding.ASCII.GetBytes(msg);
    Socket workerSocket = null;
    // for (int i = 0; i < m_workerSocketList.Count; i++)

    workerSocket = (Socket)m_workerSocketList[comboBox1.SelectedIndex];

    if (workerSocket != null)
    {
        if (workerSocket.Connected)
        {
            workerSocket.Send(byData);
        }
    }       
}

Upvotes: 1

Views: 1587

Answers (2)

Louis Waweru
Louis Waweru

Reputation: 3672

Can you try:

if (comboBox1.SelectedIndex > -1 && comboBox1.SelectedIndex < m_workerSocketList.Count)
{
    workerSocket = (Socket)m_workerSocketList[comboBox1.SelectedIndex];
}
else
{
    //message
}

Upvotes: 0

Matthew Strawbridge
Matthew Strawbridge

Reputation: 20620

Before calling workerSocket = (Socket)m_workerSocketList[comboBox1.SelectedIndex]; you need to check the value of comboBox1.SelectedIndex. If it's out of range, display your error message; only if it's in range (>= 0 and < m_workerSocketList.Count) will it be safe to use as an index into m_workerSocketList.

Upvotes: 2

Related Questions