title: Looping through GridView rows and validating each TextBox contained within an ItemTemplate
body: <p>I have a databound textbox within a gridview which enables the user to easily and quickly bulk update rows. I have tried to use the CustomValidator to validate each textbox against a SQL column but it doesn't behave the way I need it to. The CustomValidator code works properly in the TextChanged event, however it does not behave properly in the ServerValidate event (I understand why). If I leave the code in the TextChanged event handler it still allows the data to be modified when hitting the Update button I created. What can I do to validate each TextBox individually and effectively against the SQL data?</p>
  
  
  
  <pre class="lang-html prettyprint-override"><code>    &lt;ItemTemplate&gt;
  &lt;asp:TextBox ID="Account" runat="server" AutoPostBack="true" OnTextChanged="Account_TextChanged" Text='&lt;%# Bind("Account") %&gt;'&gt;&lt;/asp:TextBox&gt;
  &lt;asp:CustomValidator ID="CustomValidator1" runat="server" CssClass="CustomValidator" ValidateEmptyText="false" SetFocusOnError="True" Display="Dynamic" ControlToValidate="Account" OnServerValidate="Validate_ServerValidate" ErrorMessage="Custom Validator"&gt;&lt;/asp:CustomValidator&gt;
  &lt;/ItemTemplate&gt;
  </code></pre>
  
  <pre class="lang-cs prettyprint-override"><code>foreach (GridViewRow row in GridView2.Rows)
  {
      TextBox Account = row.FindControl("Account") as TextBox;
      CustomValidator validator = row.FindControl("CustomValidator1") as CustomValidator;
      string sAccount = Account.Text;
      using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString))
      using (SqlDataAdapter da = new SqlDataAdapter("SELECT Account Table WHERE Account = @Account", conn))
          {
                      da.SelectCommand.Parameters.Add("@Account", SqlDbType.VarChar);
                      da.SelectCommand.Parameters["@Account"].Value = sAccount;
                      DataSet ds = new DataSet();
                      da.Fill(ds);
                      if (ds.Tables[0].Rows.Count &gt; 0)
                      {
                          validator.IsValid = true;
                      }
                      else
                      {
                          validator.IsValid = false;
                      }
                  }
              }
  </code></pre>