title: How to tie a piece of code to a button click event Xamarin Android
body: <p>OVERVIEW:</p>
  
  <p>I need to create an app to send a simple string via TCP to a server on a PC. I am writing this app in Visual Studio 2015 with Xamarin. Earlier today I had gotten the TCP sending to function, but I wanted the app to look better. I downloaded a template and got to work adding back in the code. I ran into an issue, however, when I tried to run the program. It gave me Object not set to Instance error. </p>
  
  <p>Basically, I'm a newb and have no clue where to set the code that will execute when a button is pressed. Any help is appreciated, and please keep in mind that I a quite frustrated (I do apologize) and I will act kindly if the same favor is payed to me :)</p>
  
  <p>Thanks everyone, here is the code:</p>
  
  <pre><code>    using Android.App;
  using Android.Content.PM;
  using Android.Content.Res;
  using Android.OS;
  using Android.Support.V4.Widget;
  using Android.Views;
  using Android.Widget;
  
  using AndroidApp1.Fragments;
  using Android.Support.V7.App;
  using Android.Support.V4.View;
  using Android.Support.Design.Widget;
  using System.IO;
  using System;
  using System.Runtime.InteropServices.ComTypes;
  using System.Text;
  using System.Net.Sockets;
  
  namespace AndroidApp1.Activities
  {
      [Activity(Label = "Home", MainLauncher = true, LaunchMode = LaunchMode.SingleTop, Icon = "@drawable/Icon")]
      public class MainActivity : BaseActivity
      {
          TcpClient client; // Creates a TCP Client
          NetworkStream stream; //Creats a NetworkStream (used for sending and receiving data)
          byte[] datalength = new byte[4]; // creates a new byte with length 4 ( used for receivng data's lenght)
          DrawerLayout drawerLayout;
          NavigationView navigationView;
  
          protected override int LayoutResource
          {
              get
              {
  
                  return Resource.Layout.main;
              }
          }
          protected override void OnCreate(Bundle savedInstanceState)
          {
  
              base.OnCreate(savedInstanceState);
  
  
  
              drawerLayout = this.FindViewById&lt;DrawerLayout&gt;(Resource.Id.drawer_layout);
  
              //Set hamburger items menu
              SupportActionBar.SetHomeAsUpIndicator(Resource.Drawable.ic_menu);
  
              //setup navigation view
              navigationView = FindViewById&lt;NavigationView&gt;(Resource.Id.nav_view);
              Button connectButton = FindViewById&lt;Button&gt;(Resource.Id.buttonConnect);
              //handle navigation
              navigationView.NavigationItemSelected += (sender, e) =&gt;
              {
                  e.MenuItem.SetChecked(true);
  
                  switch (e.MenuItem.ItemId)
                  {
                      case Resource.Id.nav_home_1:
                          ListItemClicked(0);
                          break;
                      case Resource.Id.nav_home_2:
                          ListItemClicked(1);
                          break;
                  }
  
                  Snackbar.Make(drawerLayout, "You selected: " + e.MenuItem.TitleFormatted, Snackbar.LengthLong)
                      .Show();
  
                  drawerLayout.CloseDrawers();
              };
              SetContentView(Resource.Layout.main);
  
  
  
  
              //if first time you will want to go ahead and click first item.
              if (savedInstanceState == null)
              {
                  ListItemClicked(0);
              }
  
              connectButton.Click += (object sender, EventArgs e) =&gt;
              {
                  try
                  {
                      if (FindViewById&lt;Button&gt;(Resource.Id.buttonConnect).Text == "Connect")
                      {
                          client = new TcpClient("10.0.0.85", 21); //Trys to Connect
                          Toast.MakeText(this, "Connected", ToastLength.Short).Show();
                          //   buttonConnect.Text = "Dis-Connect";
                          //   textReceive.Text = null;
                          //   buttonSend.Enabled = true;
                      }
                      else
                      {
                          //   buttonConnect.Text = "Connect";
                          Toast.MakeText(this, "Dis-Connected", ToastLength.Short).Show();
                          client.GetStream().Close();
                          client.Close();
                      }
                  }
                  catch (Exception ex)
                  {
                      Toast.MakeText(this, ex.Message, ToastLength.Short).Show();
                  }
              };
          }
  
  
          int oldPosition = -1;
  
          private void ListItemClicked(int position)
          {
              //this way we don't load twice, but you might want to modify this a bit.
              if (position == oldPosition)
                  return;
  
              oldPosition = position;
  
              Android.Support.V4.App.Fragment fragment = null;
              switch (position)
              {
                  case 0:
                      fragment = Fragment1.NewInstance();
                      break;
                  case 1:
                      fragment = Fragment2.NewInstance();
                      break;
              }
  
              SupportFragmentManager.BeginTransaction()
                  .Replace(Resource.Id.content_frame, fragment)
                  .Commit();
          }
  
          public override bool OnOptionsItemSelected(IMenuItem item)
          {
              switch (item.ItemId)
              {
                  case Android.Resource.Id.Home:
                      drawerLayout.OpenDrawer(Android.Support.V4.View.GravityCompat.Start);
                      return true;
              }
              return base.OnOptionsItemSelected(item);
          }
  
          public void clientSend(string msg)
          {
              try
              {
                  stream = client.GetStream(); //Gets The Stream of The Connection
                  byte[] data; // creates a new byte without mentioning the size of it cuz its a byte used for sending
                  data = Encoding.Default.GetBytes(msg); // put the msg in the byte ( it automaticly uses the size of the msg )
                  int length = data.Length; // Gets the length of the byte data
                  byte[] datalength = new byte[4]; // Creates a new byte with length of 4
                  datalength = BitConverter.GetBytes(length); //put the length in a byte to send it
                  stream.Write(datalength, 0, 4); // sends the data's length
                  stream.Write(data, 0, data.Length); //Sends the real data
              }
              catch (Exception ex)
              {
                  Toast.MakeText(this, ex.Message, ToastLength.Short).Show();
              }
  
  
          }
  
  
  
  
  
      }
  }
  </code></pre>
  
  <p>Now here is the design code:</p>
  
  <pre><code>    &lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;GridLayout xmlns:p1="http://schemas.android.com/apk/res/android"
      p1:layout_width="match_parent"
      p1:layout_height="match_parent"
      p1:id="@+id/gridLayout1"&gt;
      &lt;TextView
          p1:text="Home Team"
          p1:textAppearance="?android:attr/textAppearanceMedium"
          p1:id="@+id/textView1"
          p1:layout_marginLeft="21.0dp" /&gt;
      &lt;Button
          p1:text="+"
          p1:id="@+id/buttonHomeScoreAdd"
          p1:layout_marginRight="43.5dp"
          p1:layout_marginLeft="-100dp"
          p1:layout_marginTop="55.5dp"
          p1:layout_marginBottom="12.0dp" /&gt;
      &lt;Button
          p1:text="-"
          p1:id="@+id/buttonHomeScoreMinus"
          p1:layout_marginRight="43.5dp"
          p1:layout_marginLeft="0.0dp"
          p1:layout_marginTop="55.5dp"
          p1:layout_marginBottom="12.0dp" /&gt;
      &lt;Button
          p1:text="Connect"
          p1:id="@+id/buttonConnect"
          p1:layout_marginTop="481.5dp"
          p1:layout_width="300dp"
          p1:layout_marginRight="0dp"
          p1:layout_marginLeft="-250dp" /&gt;
  &lt;/GridLayout&gt;
  </code></pre>
  
  <p>**To clarify, I would like to know where to put the code that will tie an object to a button event (foo += foo). It seems that the view doesn't get loaded in time to function properly in its current location. **</p>