title: Object reference not set to an instance of an object database username validation
body: <p>I can not understand the logic behind the connectionString command. I am attempting to make a username registration page that checks the availability of a user name before submitting. I have followed my ASP.NET unleashed textbook to a tee, but still I get the "object reference not set" error. Do I have to name my database and table accordingly here or am I missing something else? I have been searching the internet like crazy trying to make sense of this, but I am just confusing myself. Any advise would be greatly appreciated. </p>
  
  <p>Here are my ShowAjaxValidator.aspx and AjaxValidator.cs pages:</p>
  
  <pre><code>&lt;%@ Page Language="C#" %&gt;
  &lt;%@ Register TagPrefix="custom" Namespace="myControls" %&gt;
  &lt;%@ Import Namespace="System.Data.SqlClient" %&gt;
  &lt;%@ Import Namespace="System.Web.Configuration" %&gt;
  &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
  &lt;script runat="server"&gt;
  
      /// &lt;summary&gt;
      /// Validation function that is called on both the client and server
      /// &lt;/summary&gt;
      protected void AjaxValidator1_ServerValidate(object source, ServerValidateEventArgs args)
      {
          if (UserNameExists(args.Value))
              args.IsValid = false;
          else
              args.IsValid = true;
      }
  
      /// &lt;summary&gt;
      /// Returns true when user name already exists
      /// in Users database table
      /// &lt;/summary&gt;
      private bool UserNameExists(string userName)
      {
          string conString =
  WebConfigurationManager.ConnectionStrings["UsersDB"].ConnectionString;
          SqlConnection con = new SqlConnection(conString);
          SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM Users WHERE UserName=@UserName", con);
          cmd.Parameters.AddWithValue("@UserName", userName);
          bool result = false;
          using (con)
          {
              con.Open();
              int count = (int)cmd.ExecuteScalar();
              if (count &gt; 0)
                  result = true;
          }
          return result;
      }
  
      /// &lt;summary&gt;
      /// Insert new user name to Users database table
      /// &lt;/summary&gt;
      protected void btnSubmit_Click(object sender, EventArgs e)
      {
          string conString =
  WebConfigurationManager.ConnectionStrings["UsersDB"].ConnectionString;
          SqlConnection con = new SqlConnection(conString);
          SqlCommand cmd = new SqlCommand("INSERT Users (UserName,FavoriteColor) VALUES (@UserName,@FavoriteColor)", con);
          cmd.Parameters.AddWithValue("@UserName", txtUserName.Text);
          cmd.Parameters.AddWithValue("@FavoriteColor", txtFavoriteColor.Text);
          using (con)
          {
              con.Open();
              cmd.ExecuteNonQuery();
          }
          txtUserName.Text = String.Empty;
          txtFavoriteColor.Text = String.Empty;
      }
  &lt;/script&gt;
  &lt;html xmlns="http://www.w3.org/1999/xhtml" &gt;
  &lt;head id="Head1" runat="server"&gt;
      &lt;title&gt;Show AjaxValidator&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;form id="form1" runat="server"&gt;
      &lt;div&gt;
  
      &lt;asp:Label
          id="lblUserName"
          Text="User Name:"
          AssociatedControlID="txtUserName"
          Runat="server" /&gt;
      &lt;asp:TextBox
          id="txtUserName"
          Runat="server" /&gt;
      &lt;custom:AjaxValidator
          id="AjaxValidator1"
          ControlToValidate="txtUserName"
          Text="User name already taken!"
          OnServerValidate="AjaxValidator1_ServerValidate"
          Runat="server" /&gt;
  
      &lt;br /&gt;&lt;br /&gt;
      &lt;asp:Label
          id="lblFavoriteColor"
          Text="Favorite Color:"
          AssociatedControlID="txtFavoriteColor"
          Runat="server" /&gt;
      &lt;asp:TextBox
          id="txtFavoriteColor"
          Runat="server" /&gt;
  
      &lt;br /&gt;&lt;br /&gt;
      &lt;asp:Button
          id="btnSubmit"
          Text="Submit"
          Runat="server" OnClick="btnSubmit_Click" /&gt;
  
      &lt;/div&gt;
      &lt;/form&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>AjaxValidator.cs</p>
  
  <pre><code>using System;
  using System.Web;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  
  namespace myControls
  {
      /// &lt;summary&gt;
      /// Enables you to perform custom validation on both the client and server
      /// &lt;/summary&gt;
      public class AjaxValidator : BaseValidator, ICallbackEventHandler
      {
          public event ServerValidateEventHandler ServerValidate;
  
          string _controlToValidateValue;
  
          protected override void OnPreRender(EventArgs e)
          {
              String eventRef = Page.ClientScript.GetCallbackEventReference
                (
                  this,
                  "",
                  "",
                  ""
                );
  
              // Register include file
              String includeScript =
                    Page.ResolveClientUrl("~/ClientScripts/AjaxValidator.js");
              Page.ClientScript.RegisterClientScriptInclude("AjaxValidator",
                    includeScript);
  
              // Register startup script
              String startupScript =
  String.Format("document.getElementById('{0}').evaluationfunction = 'AjaxValidatorEvaluateIsValid';", this.ClientID);
              Page.ClientScript.RegisterStartupScript(this.GetType(), "AjaxValidator", startupScript, true);
  
              base.OnPreRender(e);
          }
  
          /// &lt;summary&gt;
          /// Only do the AJAX on browsers that support it
          /// &lt;/summary&gt;
          protected override bool DetermineRenderUplevel()
          {
              return Context.Request.Browser.SupportsCallback;
          }
  
          /// &lt;summary&gt;
          /// Server method called by client AJAX call
          /// &lt;/summary&gt;
          public string GetCallbackResult()
          {
              return ExecuteValidationFunction(_controlToValidateValue).ToString();
          }
  
          /// &lt;summary&gt;
          /// Return callback result to client
          /// &lt;/summary&gt;
          public void RaiseCallbackEvent(string eventArgument)
          {
              _controlToValidateValue = eventArgument;
          }
  
          /// &lt;summary&gt;
          /// Server-side method for validation
          /// &lt;/summary&gt;
          protected override bool EvaluateIsValid()
          {
              string controlToValidateValue =
  this.GetControlValidationValue(this.ControlToValidate);
              return ExecuteValidationFunction(controlToValidateValue);
          }
  
          /// &lt;summary&gt;
          /// Performs the validation for both server and client
          /// &lt;/summary&gt;
          private bool ExecuteValidationFunction(String controlToValidateValue)
          {
              ServerValidateEventArgs args = new ServerValidateEventArgs (controlToValidateValue, this.IsValid);
              if (ServerValidate != null)
                  ServerValidate(this, args);
              return args.IsValid;
          }
  
      }
  
  }
  </code></pre>
  
  <p>The error I am running into points to the part of the .aspx file that says:</p>
  
  <pre><code>string conString =
  WebConfigurationManager.ConnectionStrings["UsersDB"].ConnectionString;
  </code></pre>
  
  <p>The error says that a null exception was unhanded by the user and "Object reference not set to an instance of an object." </p>
  
  <p>I tried to add the connectionStrings to the web.config file, but I am not sure if it is using the correct syntax. Could you please tell me if this is what you were saying:</p>
  
  <pre><code>&lt;?xml version="1.0"?&gt;
  &lt;!--
    For more information on how to configure your ASP.NET application, please visit
    http://go.microsoft.com/fwlink/?LinkId=169433
    --&gt;
  &lt;configuration&gt;
    &lt;connectionStrings&gt;
      &lt;add name="UsersDB"
           providerName="System.Data.SqlClient"
           connectionString="Data Source=.\SQLExpress;
                      AttachDbFilename=|DataDirectory|UsersDB.mdf;
                      Integrated Security=True;User Instance=True" /&gt;
    &lt;/connectionStrings&gt;
    &lt;system.web&gt;
      &lt;compilation debug="true" targetFramework="4.0"/&gt;
    &lt;/system.web&gt;
  &lt;/configuration&gt;
  </code></pre>
  
  <p>I am now getting an SqlException that says:
  An attempt to attach an auto-named database for file C:\Users\Mike\Documents\Visual Studio 2010\WebSites\Validation_Attempt\App_Data\UsersDB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.</p>
  
  <p>I am very new to ASP and C#. Edit for bronze.</p>