c#参数超出范围未处理,原因是SelectedIndex
本文关键字:SelectedIndex 未处理 参数 范围 | 更新日期: 2023-09-27 18:16:48
由于没有编号或没有选择连接的客户端索引编号而单击按钮时发生'Argument out of range was unhandled'错误。错误提示:
workerSocket = (Socket)m_workerSocketList[comboBox1.SelectedIndex];
我想给一个消息框说'请选择一个正确的数字'。应该编写什么代码来处理这个错误?
下面是代码: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);
}
}
}
在调用workerSocket = (Socket)m_workerSocketList[comboBox1.SelectedIndex];
之前,需要检查comboBox1.SelectedIndex
的值。如果超出范围,则显示错误消息;只有当它在范围(>= 0
和< m_workerSocketList.Count
)中,才可以安全地用作m_workerSocketList
的索引。
你可以试试:
if (comboBox1.SelectedIndex > -1 && comboBox1.SelectedIndex < m_workerSocketList.Count)
{
workerSocket = (Socket)m_workerSocketList[comboBox1.SelectedIndex];
}
else
{
//message
}