title: asp.net Dropdownlist Customvalidator servervalidate referencing control
body: <p>I have a dropdownlist that I populate from the DB, and depending on business logic I need to be able to validate the selected item (TEXT) from the dropdownlist with server side vaildation. Requirements state I cannot simply filter it out as part of the SQL statement. The solution I have been trying to get to work is to simply create a customvalidation in the code behind.</p>
  
  <p>The validation is called, BUT I cannot figure out how to reference the ddl DataTextField value for the item selected. When I try and do the server side code below the asp.net system states that my dropdownlist does not exist within the detailsview and provides a red underline as a result. In this instance it will always be insertmode.</p>
  
  <p>Suggestions</p>
  
  <hr>
  
  <p>ASP Code</p>
  
  <hr>
  
  <pre><code>&lt;asp:DetailsView ID="dtlSample" runat="server" AutoGenerateEditButton="true" AutoGenerateRows="false"&gt;
        &lt;Fields&gt;
  </code></pre>
  
  <p>.
  .
  .</p>
  
  <pre><code>        &lt;asp:TemplateField HeaderText="Position"&gt;
            &lt;ItemTemplate&gt;
              &lt;%# Eval("Age") %&gt;
            &lt;/ItemTemplate&gt;
            &lt;EditItemTemplate&gt;
              &lt;asp:DropDownList ID="ddlPosition" runat="server" AutoPostBack="True" 
                  LDataSource="Select Position, PositionId from ...." DataTextField="Position" DataValueField="PositionId"
                   &gt;&lt;/asp:DropDownList&gt;
            &lt;/EditItemTemplate&gt;
            &lt;InsertItemTemplate&gt;
              &lt;asp:DropDownList ID="ddlPosition" runat="server" AutoPostBack="True" 
                  LDataSource="Select Position, PositionId from ...." DataTextField="Position" DataValueField="PositionId"
                   &gt;&lt;/asp:DropDownList&gt;
            &lt;/InsertItemTemplate&gt;
      &lt;asp:CustomValidator ID="cvPos" Display="Dynamic" ControlToValidate = "DDLPosition"
            OnServerValidate="ddlPos_Check" runat="server" ForeColor="Red" ErrorMessage="My error message"&gt;&lt;/asp:CustomValidator&gt;
          &lt;/asp:TemplateField&gt;
        &lt;/Fields&gt;
  </code></pre>
  
  <p></p>
  
  <p>CODE BEHIND</p>
  
  <pre><code>protected void ddlPos_Check(object sender, ServerValidateEventArgs args)
  </code></pre>
  
  <p>{</p>
  
  <pre><code>    if (ddPosition.SelectedItem.Text.Contains("some value")            
          args.IsValid = false;         
      else           
          args.IsValid = true;    
  </code></pre>
  
  <p>}</p>