title: Null Reference Exception in SQL Query output
body: <p>After struggling with pulling certain info from a SQL Database to use in C# code to do some permission checking, I have decided to go back to basics and learn how to do it properly and slowly build on my skills so I can eventually do what I need to do.  The object of the below code is to grab the current Active Directory user, then go into a SQL table that contains usernames and other info, find one that matches and then display it in a MessageBox.</p>
  
  <pre><code>string currentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
  
  using (var cn = new SqlConnection(ConfigurationManager.ConnectionStrings["HSEProjRegConnectionString1"].ConnectionString))
  using (var cmd = new SqlCommand())
  {
      cn.Open();
      cmd.Connection = cn;
      cmd.CommandType = CommandType.Text;
      cmd.CommandText = "SELECT username FROM [tbl_Person] WHERE [username] LIKE '@currentUser'";
  
      SqlParameter param = new SqlParameter();
      cmd.Parameters.Add("@currentUser", SqlDbType.Char).Value = currentUser;
  
      MessageBox.Show("{0}", Convert.ToString((int)cmd.ExecuteScalar()));
  
      cn.Close();
  }
  </code></pre>
  
  <p>Something is wrong though.  I get the following error and Stack Trace.  Line 38 is the MessageBox line.</p>
  
  <p>System.NullReferenceException: Object reference not set to an instance of an object.</p>
  
  <pre><code>[NullReferenceException: Object reference not set to an instance of an object.]
  HSE_project_Register.admin.Page_Load(Object sender, EventArgs e) in S:\IT\Development\Visual Studio Projects\HSE Project Register\admin\admin.aspx.cs:38
  System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
  System.Web.UI.Control.LoadRecursive() +71
  System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3064
  </code></pre>
  
  <p>What is causing the Null Reference Exception in that code?  If the answer is in the Stack Trace, could someone please explain that to me?  I find the Stack Trace extremely confusing.</p>