title: If text box value is null then set dropdown list to null
body: <p>I have a page in C# on .NET that has a dropdown menu that is populated from a database the dropdown contains dialing codes for mobile phone numbers and defaults to 'United Kingdom (+44)'</p>
  
  <p>However I also have a mobile number box where user can enter there mobile number. At the moment if the user saves without a mobile number (which is allowed) the dialing code will still get passed to the SP and ultimately be saved.</p>
  
  <p>I want to find a way to stop this happening so if a user does not enter a mobile number the dialing code is set to null when entered in the database.</p>
  
  <p>What is the best way to do this?</p>
  
  <p>This is the C#</p>
  
  <pre><code>    using System;
  using System.Collections;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Drawing;
  using System.Text;
  using System.Web;
  using System.Web.SessionState;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Web.UI.HtmlControls;
  using Dnuk.Core.DataAccess.UserOptIn;
  using Dnuk.Core.Entities2;
  using Dnuk.Core.DataAccess.CommonData;
  using Dnuk.Core.DataAccess.Framework;
  
  
  
  namespace Registration
  {
  
      /// &lt;summary&gt;
      /// Summary description for Step2.
      /// &lt;/summary&gt;
      public partial class Step2 : Basepage
      {
  
          protected int countryid = 240;
  
          protected AJAXFunctions m_AJAXFunctions;
  
  
          protected void Page_Load(object sender, System.EventArgs e)
          {
  
              StringBuilder helptext = new StringBuilder();
              helptext.AppendLine("&lt;span class='bluetext2'&gt;Your password must:-&lt;/span&gt;");
              helptext.AppendLine("");
              helptext.AppendLine("&lt;ul class='bluetext2'&gt;");
              helptext.AppendLine("   &lt;li&gt;Have at least 9 characters&lt;/li&gt;");
              helptext.AppendLine("    &lt;li&gt;Contain mixed case letters&lt;/li&gt;");
              helptext.AppendLine("    &lt;li&gt;Contain at least 1 number OR a special character&lt;/li&gt;");
              helptext.AppendLine("&lt;/ul&gt;");
              helptext.AppendLine("");
              helptext.AppendLine("&lt;p class='bluetext2'&gt;Allowed characters are: a-z, A-Z, 0-9, and these special characters: !@#$*^().,{}[]~-&lt;/p&gt;");
              helptext.AppendLine("");
              helptext.AppendLine("&lt;span class='bluetext2'&gt;Not accepted:-&lt;/span&gt;");
              helptext.AppendLine("");
              helptext.AppendLine("&lt;ul class='bluetext2'&gt;");
              helptext.AppendLine("    &lt;li&gt;the word 'password'&lt;/li&gt;");
              helptext.AppendLine("    &lt;li&gt;using your username&lt;/li&gt;");
              helptext.AppendLine("&lt;/ul&gt;");
  
              Helpicon11.Text = helptext.ToString();
  
              m_AJAXFunctions = new AJAXFunctions();
              m_AJAXFunctions.Register();
  
              if (!Page.IsPostBack)
              {
                  ddlSpecialityList.Attributes.Add("onchange", "SpecialityList_Change();");
                  lsbSubSpecialityUser.Style.Add("width", "200px");
                  imbNext.Attributes.Add("onclick", "return Validation();");
                  ddlProfessionalStatusList.Attributes.Add("onchange", "CheckProfStatusSeniority();");
                  ddlSeniorityList.Attributes.Add("onchange", "CheckProfStatusSeniority();");
                  ddlCountry.Attributes.Add("onchange", "ChangeCountry();");
                  FillData();
                  FillUserData();
              }
          }
  
  
          protected void ddlSeniorityList_Fill()
          {
              ddlSeniorityList.DataTextField = "name";
              ddlSeniorityList.DataValueField = "seniorityid";
  
              using (DBAccess db = new DBAccess())
              {
                  ddlSeniorityList.DataSource = (db.GetSpecialitySeniorityList(countryid)).Tables[0];
              }
  
              ddlSeniorityList.DataBind();
              ddlSeniorityList.Items.Insert(0, new ListItem("please select", "0"));
          }
  
  
          protected void ddlSpecialityList_Fill()
          {
              ddlSpecialityList.DataTextField = "name";
              ddlSpecialityList.DataValueField = "specialityid";
  
              using (DBAccess db = new DBAccess())
              {
                  ddlSpecialityList.DataSource = (db.GetSpecialitySeniorityList(countryid)).Tables[1];
              }
  
              ddlSpecialityList.DataBind();
              ddlSpecialityList.Items.Insert(0, new ListItem("please select", "0"));
          }
  
  
          protected void ddlProfessionalStatusList_Fill()
          {
              ddlProfessionalStatusList.DataTextField = "title";
              ddlProfessionalStatusList.DataValueField = "ProfStatusId";
  
              using (DBAccess db = new DBAccess())
              {
                  ddlProfessionalStatusList.DataSource = db.GetProfessionalStatusList();
              }
  
              ddlProfessionalStatusList.DataBind();
          }
  
  
          protected void ddlCountry_Fill()
          {
              ddlCountry.DataTextField = "countryname";
              ddlCountry.DataValueField = "countryid";
  
              using (DBAccess db = new DBAccess())
              {
                  ddlCountry.DataSource = db.GetCountryList();
              }
  
              ddlCountry.DataBind();
              ddlCountry.Items.Insert(0, new ListItem("please select", "0"));
          }
  
  
          protected void cLVOptins_Fill()
          {
              UserOptInDAO userOptInDAO = new UserOptInDAO();
              cLVOptins.DataSource = userOptInDAO.GetRegistrationOptInList();
              cLVOptins.DataBind();
          }
  
  
          private void FillData()
          {
              ddlSeniorityList_Fill();
              ddlSpecialityList_Fill();
              ddlProfessionalStatusList_Fill();
              ddlCountry_Fill();
              cLVOptins_Fill();
          }
  
  
          protected void FillUserData()
          {
              if (Session["Registration_RegInfo"] != null)
              {
                  RegInfo ri = (RegInfo)Session["Registration_RegInfo"];
  
                  if (ddlSeniorityList.Items.FindByValue(Convert.ToString(ri.SeniorityID)) != null)
                      ddlSeniorityList.SelectedValue = Convert.ToString(ri.SeniorityID);
                  if (ddlSpecialityList.Items.FindByValue(Convert.ToString(ri.SpecialityID)) != null)
                      ddlSpecialityList.SelectedValue = Convert.ToString(ri.SpecialityID);
                  ddlProfessionalStatusList.SelectedValue = Convert.ToString(ri.ProfessionalStatusID);
                  hdnPCT_NHSID.Value = Convert.ToString(ri.PCT_NHSID);
                  hdnGP_TrustID.Value = Convert.ToString(ri.GP_TrustID);
  
                  using (DBAccess helper = new DBAccess())
                  {
                      if (ri.HPOTypeIDs != null)
                      {
                          hdnHPOTypeIDs.Value = Convert.ToString(ri.HPOTypeIDs);
                      }
                      else
                      {
                          //the default HPO types should be "All"
                          DataTable dt = helper.GetHPOTypes();
                          foreach (DataRow dr in dt.Rows)
                          {
                              hdnHPOTypeIDs.Value += Convert.ToString(dr["OrgnTypeID"]) + ",";
                          }
                          if (hdnHPOTypeIDs.Value.Length &gt; 0)
                              hdnHPOTypeIDs.Value = hdnHPOTypeIDs.Value.Substring(0, hdnHPOTypeIDs.Value.Length-1);
  
                      }
                      this.lblSelectedOrgTypes.Text = helper.GetHPOTypeNames(hdnHPOTypeIDs.Value);
                  }
  
                  ddlDialingCode.Text = ri.DialingCodeText;
                  txbPostcode.Text = ri.Postcode;
                  txbLocality.Text = ri.Locality;
                  txbAddress1.Text = ri.Address1;
                  txbAddress2.Text = ri.Address2;
                  txbCity.Text = ri.City;
                  txbCounty.Text = ri.County;
                  if (ri.CountryID != 0)
                      ddlCountry.SelectedValue = Convert.ToString(ri.CountryID);
                  else
                      ddlCountry.SelectedValue = "240";
  
                  txt_username.Value = ri.Username;
  
                  txbAltEMail.Text = ri.AltEMail;
                  if (ri.DialingCodeID != 0)
                      ddlDialingCode.SelectedValue = Convert.ToString(ri.DialingCode);
                  else
                      ddlDialingCode.SelectedValue = "240";
  
                  txbPhoneNumber.Text = ri.PhoneNumber;
                  if (ri.SubSpecialityIDs != null)
                      SubSpecialityIDs = ri.SubSpecialityIDs; 
                  txbSecWord1.Text = ri.SecWord1;
                  txbSecWord2.Text = ri.SecWord2;
  
  
                  if (ri.OptIns != null)
                  {
                      foreach (KeyValuePair&lt;Int32, bool&gt; entry in ri.OptIns)
                      {
                          foreach (ListViewItem item in cLVOptins.Items)
                          {
                              CheckBox chkBox = (CheckBox)item.FindControl("cCbOptIn");
                              Int32 optInId = Convert.ToInt32(chkBox.InputAttributes["optId"]);
  
                              if (optInId == entry.Key)
                              {
                                  chkBox.Checked = entry.Value;
                                  break;
                              }
  
                          }
                      }
                  }
  
              }
          }
  
  
          private void PutRegInfo()
          {
              if (Session["Registration_RegInfo"] != null)
              {
                  RegInfo ri = (RegInfo)Session["Registration_RegInfo"];
  
                  ri.SeniorityID = Convert.ToInt32(ddlSeniorityList.SelectedValue);
                  ri.SpecialityID = Convert.ToInt32(ddlSpecialityList.SelectedValue);
                  ri.SubSpecialityIDs = SubSpecialityIDs;
                  ri.PCT_NHSID = Convert.ToInt32(hdnPCT_NHSID.Value);
                  ri.GP_TrustID = Convert.ToInt32(hdnGP_TrustID.Value);
                  ri.HPOTypeIDs = Convert.ToString(hdnHPOTypeIDs.Value);
                  ri.ProfessionalStatusID = Convert.ToInt32(ddlProfessionalStatusList.SelectedValue);
                  ri.Postcode = txbPostcode.Text.Trim();
                  ri.Locality = txbLocality.Text.Trim();
                  ri.Address1 = txbAddress1.Text.Trim();
                  ri.Address2 = txbAddress2.Text.Trim();
                  ri.City = txbCity.Text.Trim();
                  ri.County = txbCounty.Text.Trim();
                  ri.CountryID = Convert.ToInt32(ddlCountry.SelectedValue);
  
                  ri.Username = txt_username.Value.Trim();
                  ri.Password = txt_newpassw.Value.Trim();
  
                  ri.AltEMail = txbAltEMail.Text.Trim();
                  ri.PhoneNumber = txbPhoneNumber.Text.Trim();
                  ri.DialingCodeID = Convert.ToInt32(ddlDialingCode.SelectedValue);
                  ri.DialingCode = ddlDialingCode.SelectedValue;
                  ri.DialingCodeText = ddlDialingCode.SelectedItem.Text;
                  ri.SecWord1 = txbSecWord1.Text.Trim();
                  ri.SecWord2 = txbSecWord2.Text.Trim();
  
                  // string fields
                  ri.Seniority = ddlSeniorityList.SelectedItem.Text;
                  ri.Speciality = ddlSpecialityList.SelectedItem.Text;
                  ri.SubSpecialities = SubSpecialities;
                  ri.PCT_NHS = hdnPCT_NHS.Value;
                  ri.GP_Trust = hdnGP_Trust.Value;
                  ri.ProfessionalStatus = ddlProfessionalStatusList.SelectedItem.Text;
                  ri.Country = ddlCountry.SelectedItem.Text;
  
  
                  if (ri.OptIns == null)
                      ri.OptIns = new Dictionary&lt;int, bool&gt;();
  
                  ri.OptIns.Clear();
  
                  foreach (ListViewItem item in cLVOptins.Items)
                  {
                      CheckBox chkBox = (CheckBox)item.FindControl("cCbOptIn");
                      Int32 optInId = Convert.ToInt32(chkBox.InputAttributes["optId"]);
  
                      ri.OptIns.Add(optInId, chkBox.Checked);
                  }                
  
                  Session.Add("Registration_RegInfo", ri);
              }
          }
  
  
          protected void imbNext_Click(object sender, System.Web.UI.ImageClickEventArgs e)
          {
  
  
              // check passwords
              using (DBAccess da = new DBAccess())
              {
                  UP_Validation_Username.Username upv_uname = new UP_Validation_Username.Username();
                  UP_Validation_Password.Password upv_pass = new UP_Validation_Password.Password();
  
                  string codes = string.Empty;
                  string codes1 = string.Empty;
                  string codes2 = string.Empty;
  
                  System.Configuration.AppSettingsReader _configReader = new System.Configuration.AppSettingsReader();
                  string skey = _configReader.GetValue("UP_SecurityKey", typeof(string)).ToString();
  
                  codes1 = upv_pass.Password_Validation_Lite(skey, txt_username.Value, txt_newpassw.Value, txt_newpassw1.Value);
                  codes2 = upv_uname.Username_Validation(skey, txt_username.Value, 0);
  
                  if (codes1 == "1" &amp;&amp; codes2 == "1")
                  {
                      codes = "1";
                  }
                  else
                  {
                      codes = codes1 + "," + codes2;
                      char[] comma = new char[] { ',' };
                      codes = codes.TrimEnd(comma);
                      codes = codes.TrimStart(comma);
                  }
  
                  if (codes != "1")
                  {
                      err_username.InnerHtml = "";
                      err_newpassw.InnerHtml = "";
                      err_newpassw1.InnerHtml = "";
  
                      DataSet ds = new DataSet();
                      ds = upv_pass.GetErrorMessages(skey, codes);
  
                      if (ds.Tables.Count &gt; 0)
                      {
                          DataTable dt = new DataTable();
                          dt = ds.Tables[0];
  
                          foreach (DataRow dr in dt.Rows)
                          {
                              switch (dr["type"].ToString())
                              {
                                  case "username":
                                      err_username.InnerHtml = err_username.InnerHtml + dr["message"].ToString() + "&lt;br/&gt;";
                                      break;
                                  case "newpassword":
                                      err_newpassw.InnerHtml = err_newpassw.InnerHtml + dr["message"].ToString() + "&lt;br/&gt;";
                                      break;
                                  case "newpassword1":
                                      err_newpassw1.InnerHtml = err_newpassw1.InnerHtml + dr["message"].ToString() + "&lt;br/&gt;";
                                      break;
                              }
                          }
                      }
                  }
                  else
                  {
                      PutRegInfo();
                      if (Request.QueryString["redirecttoansaedu"] != null)
                          Response.Redirect("Step3.aspx?redirecttoansaedu=1", true);
                      else Response.Redirect("Step3.aspx", true);
                  }
  
              }
  
          }
  
  
          protected int[] SubSpecialityIDs
          {
              get
              {
                  const char DELIMITER = '\x0001';
  
                  string[] sArray;
                  if (hdnSubSpecialityIDs.Value == "")
                      sArray = new string[0];
                  else
                      sArray = hdnSubSpecialityIDs.Value.Split(DELIMITER);
  
                  return ConvertArray_ToInt(sArray);
              }
              set
              {
                  const char DELIMITER = '\x0001';
  
                  hdnSubSpecialityIDs.Value = String.Join(Convert.ToString(DELIMITER), ConvertArray_ToString(value));
              }
          }
  
  
          protected string[] SubSpecialities
          {
              get
              {
                  const char DELIMITER = '\x0001';
                  if (hdnSubSpecialityIDs.Value == "")
                      return new string[0];
                  else
                      return hdnSubSpecialities.Value.Split(DELIMITER);
              }
              set
              {
                  const char DELIMITER = '\x0001';
  
                  hdnSubSpecialities.Value = String.Join(Convert.ToString(DELIMITER), value);
              }
          }
  
  
          protected int[] ConvertArray_ToInt(object[] array)
          {
              int[] result = new int[array.Length];
  
              for (int i = 0; i &lt; array.Length; i++)
                  result[i] = Convert.ToInt32(array[i]);
  
              return result;
          }
  
  
          protected string[] ConvertArray_ToString(int[] array)
          {
              string[] result = new string[array.Length];
  
              for (int i = 0; i &lt; array.Length; i++)
                  result[i] = Convert.ToString(array[i]);
  
              return result;
          }
  
  
          protected void cLVOptins_ItemDataBound(object sender, ListViewItemEventArgs e)
          {
              if (e.Item.ItemType == ListViewItemType.DataItem || e.Item.ItemType == ListViewItemType.EmptyItem)
              {
                  UserOptIn optIn = (UserOptIn)e.Item.DataItem; 
  
                  //Hide the help icon when there is no helptext
                  if (optIn.HelpText == string.Empty)
                  {
                      Registration.Controls.HelpIcon helpIcon = (Registration.Controls.HelpIcon)e.Item.FindControl("cHelpIconOptIn");
                      helpIcon.Visible = false;
                  }
  
                  //Remove indent where there is no parent
                  if (optIn.ParentId == 0)
                  {
                      Label cLblIndent = (Label)e.Item.FindControl("cLblIndent");
                      cLblIndent.Visible = false;
                  }
  
                  CheckBox chkBox = (CheckBox)e.Item.FindControl("cCbOptIn");
                  chkBox.Checked = optIn.Default;
                  chkBox.InputAttributes.Add("optId", optIn.Id.ToString());
  
                  //bit of a hack
                  if (optIn.Description.IndexOf("Market Research invitations") &gt; -1)
                  {
                      chkBox.Text = chkBox.Text + "&lt;div class=\"greytext1 optInIndent\" optparentid=\"1\"&gt;You will receive invitations through the Doctors.net.uk website or by e-mail. Some surveys are also conducted by telephone. To ensure you are invited to these surveys as well, please indicate this below.&lt;/div&gt;";
                  }
  
              }
          }
  
          protected void DialingCodeDropDown_Init(object sender, EventArgs e)
          {
              CommonDataSource cds = new CommonDataSource();
              cds.SQLExecutorSource = new SQLHelperExecutorSource();
              List&lt;RefCountry&gt; countries = cds.RefCountries();
              List&lt;ListItem&gt; adjustedCountriesList = new List&lt;ListItem&gt;();    
  
  
              foreach (RefCountry country in countries)
              {
                  if (country.DiallingCode.Trim() == "")
                      continue;
  
                  ListItem item = new ListItem();
                  item.Value = country.CountryID.ToString();
                  item.Text = String.Format("{0} (+{1})", country.CountryName, country.DiallingCode.Trim());
                  adjustedCountriesList.Add(item);               
              }
  
  
              ddlDialingCode.DataSource = adjustedCountriesList;            
              ddlDialingCode.DataBind();  
  
  
          }
  
          #region Web Form Designer generated code
          override protected void OnInit(EventArgs e)
          {
              //
              // CODEGEN: This call is required by the ASP.NET Web Form Designer.
              //
              InitializeComponent();
              base.OnInit(e);
          }
  
          /// &lt;summary&gt;
          /// Required method for Designer support - do not modify
          /// the contents of this method with the code editor.
          /// &lt;/summary&gt;
          private void InitializeComponent()
          {    
  
          }
          #endregion
      }
  }
  </code></pre>
  
  <p>This is the mobilephone number text box defined in the HTML</p>
  
  <pre><code>                    &lt;tr&gt;                                
                          &lt;td align="right" valign="middle" class="bluetext2b"&gt;Mobile phone number&lt;/td&gt;
                          &lt;td&gt;&lt;uc:HelpIcon id="Helpicon14" runat="server" Title="Mobile phone number" Text="Add your mobile number including the '0' and with no spaces. If you are not resident in the UK, please ensure you change the international dialling code to the appropriate country. Please note: Your mobile number will not be shared with a third party. If you opt in to take part in Market Research telephone surveys, this field will be mandatory. ."&gt;&lt;/uc:HelpIcon&gt;&amp;nbsp;&lt;/td&gt;
                          &lt;td&gt;&lt;asp:DropDownList DataTextField="Text" DataValueField="Value" ID="ddlDialingCode" Runat="server" CssClass="myinput1" OnInit="DialingCodeDropDown_Init"&gt;&lt;/asp:DropDownList&gt;&lt;/td&gt;
                      &lt;/tr&gt;
                      &lt;tr&gt;
                          &lt;td&gt;&lt;/td&gt;
                          &lt;td&gt;&lt;/td&gt;
                          &lt;td&gt;&lt;asp:TextBox ID="txbPhoneNumber" Runat="server" onkeypress="return /\d/.test(String.fromCharCode(((event||window.event).which||(event||window.event).which)));" MaxLength="11"&gt;&lt;/asp:TextBox&gt;&lt;/td&gt;
                      &lt;/tr&gt;
  </code></pre>