Object reference not set to an instance of an object button press event [duplicate]

China☆狼群 提交于 2019-12-14 03:28:30

问题


I'm getting an error message and I don't know how to fix it. This is the original code I have:

private void SendMessage(Command cmd, EndPoint sendToEP)
{
    try
    {
        //Create the message to send.
        Data msgToSend = new Data();

        //msgToSend.strName = txtName.Text;   //Name of the user.
        msgToSend.cmdCommand = cmd;         //Message to send.
        msgToSend.vocoder = vocoder;        //Vocoder to be used.

        byte[] message = msgToSend.ToByte();

        //Send the message asynchronously.
        clientSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, sendToEP, new AsyncCallback(OnSend), null);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "UniProject-SendMessage ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

The error message is (button press event)

Object reference not set to an instance of an object.

Why am I getting this error message and how can i fix it?


回答1:


Every time you get such an error (a NullReferenceException), there is something in your code that is set to null. You have to look at your code and determine:

  1. On which line (in which method) does the error occur?
  2. What variables on that line are reference types or nullable value types?
    Normal value types (e.g. struct, or integers, floats, doubles) cannot be null.
  3. Of those variables, which could possibly be null?
  4. Where are those variables possibly set to null?
    For example, a method argument, a value returned from a method, or the result of the as operator can result in a variable being null.

If none of those is the case, you might have (although unlikely) a method that is throwing this exception. The .NET base class methods generally don't throw such an exception, and if your code does throw it, your stack trace should bring you to the deepest method and line that does that.



来源:https://stackoverflow.com/questions/15513930/object-reference-not-set-to-an-instance-of-an-object-button-press-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!