Click here to Skip to main content
15,569,319 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Could someone shed some light on this problem for me, please?
I have a SocketListener and a Client winforms apps, they're based on the examples from MS: client, listener.

This Send method is done programmatically:
private void Send(Socket handler, String data)
    // Convert the string data to byte data using ASCII encoding.  
    byte[] byteData = Encoding.ASCII.GetBytes(data);

    // Begin sending the data to the remote device.  
    handler.BeginSend(byteData, 0, byteData.Length, 0,
                      new AsyncCallback(SendCallback), handler);
I would like to do it with a button.

What I have tried:

private void btnTcp1_Click(object sender, EventArgs e)
    string data = "";
    Socket handler;
    data = tBoxTcpSend.Text;
    byte[] byteData = Encoding.ASCII.GetBytes(data);

    handler.BeginSend(byteData, 0, byteData.Length, 0,
                      new AsyncCallback(SendCallback), handler);
I have tried this, but I'm getting: Use of unassigned local variable 'handler'.
I also tried to make a copy of Send method, and assign it to btnTcp1 click event, but that doesn't work either.
Updated 20-Mar-21 17:43pm

1 solution

Yes, because you have declared the local variable handler, but you never initialised it to a valid reference. Look at you Send method, which takes a handler as its first input parameter. You need to get the same reference passed in to your button's event handler.
Share this answer
Richard MacCutchan 19-Feb-21 8:53am    
You cannot just randomly put lines of code and expressions anywhere you want; there are rules to be followed. An event handler has a specific form which you must adhere to. If you want other parameters then you have to save them somewhere in your class and refer to them by name.
Richard MacCutchan 19-Feb-21 9:52am    
Yes, in any C# tutorial.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900