• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 478
  • Last Modified:

How to validate a dropdown list against a textbox in a asp.net gridview

OK I have a ASP.NET Gridview that has 6 rows. In each row there is a textbox and a dropdown list.  The grid is based off of a order id where the textbox allows the user to enter in a tracking number and a dropdown list  allows the user to enter in a tracking type (i.e. Fed EX, UPS...etc). Each row in the gridview has a different quantity and part number (the reason for the multiple rows).  So, the issue that I keep running into is that each row's textbox and dropdown list has the same ID. So when I put in the asp compare validator control the contol validates each textbox and dropdown list in every row in the gridview. When i only want the compare validator control to validate the textbox and dropdown list for the row that the user is on. I have tried several suggestions that i have googled for an none seem to work. However, i am new to ASP.NET, C# and JavaScript and so i admit I am not a stong developer and need lots of help.
What I need the validator to do......when the user enters in a tracking number in row two and row 6 (the gridview has 6 rows) the dropdown list requiers the user to select a tracing tyoe from the list.  If the user does not select a tracking type from the list on row 2 and row 6 amd then clicks on the submit button the compare validor then writes out the error message.
My ASP. NET Code:
 <asp:Label ID="lblMessage" runat="server" Font-Bold="true"></asp:Label>
  <hr />
        <asp:GridView ID="gvParent" runat="server" AutoGenerateColumns="False"
            AlternatingRowStyle-BackColor="#f7f6f3" EmptyDataText="No mathcfound!"
             CellPadding="5"  BorderStyle="Groove" BorderWidth="1px" datakeynames="GTRI_shippinginformationid"  
              ForeColor="#333333" GridLines="None" HeaderStyle-Wrap="false"
            CssClass="gridLines" AllowPaging="True" OnPageIndexChanging="gvParent_PageIndexChanging"
            PageSize="50" onrowcreated="gvParent_RowCreated"
            onrowcommand="gvParent_RowCommand" EnableModelValidation="True"
            onrowdatabound="gvParent_RowDataBound" Width="450px">
            <HeaderStyle Font-Size="18px" />
            <RowStyle BackColor="White" ForeColor="Black"  />
               <Columns>
                   <asp:TemplateField HeaderText="Tracking #">
                    <ItemTemplate>
                      <asp:TextBox ID="txtTrackingNumb" runat="server" Text='<%# Eval("GTRI_TrackingNumbers").ToString() %>'  />
                    </ItemTemplate>
                  </asp:TemplateField>
                   <asp:TemplateField HeaderText="Tracking Type">
                  <ItemTemplate>
                  <asp:DropDownList ID="ddlTrackingType" runat="server" AutoPostBack="false" SelectedValue='<%# Eval("Gtri_TrackingType") %>'   >
                   <asp:ListItem Text="Select..." Value="0" />
                   <asp:ListItem Text="Fed Ex" Value="1" />  
                   <asp:ListItem Text="UPS" Value="2" />  
                   <asp:ListItem Text="Other" Value="3" />                        
                  </asp:DropDownList>
                  <asp:CompareValidator id="CompareValidator1" ControlToValidate="ddlTrackingType" ControlToCompare="txtTrackingNumb" runat="server" >*</asp:CompareValidator>
                  </ItemTemplate>
                  </asp:TemplateField>
                  </Columns>        
        </asp:GridView>
    </script>            
   </div>
    <hr />
        <br />
        <br />  
       <asp:Button ID="Button1" Text="Submit" runat="server"  onclick="btnSubmit_Click1" />

Some of rhe examples that I have tried are: (but none have worked)
JavaScript and ASP.NET
<script type="text/javascript">
        $(document).ready(function () {
            $('.TrackingNo').live('blur', function () {
                //alert(1);
                if (jQuery.trim($(this).val()) != '')
                    $(this).parent().find('select[id$="ddlTrackingType"]').attr("disabled", "disabled");
                else
                    $(this).parent().find('select[id$="ddlTrackingType"]').removeAttr("disabled");
            });
        });    
    </script>
 <asp:TemplateField HeaderText="Tracking #">
                    <ItemTemplate>
                      <asp:TextBox ID="txtTrackingNumb" runat="server" Text='<%# Eval("GTRI_TrackingNumbers").ToString() %>'  />
                    </ItemTemplate>
                  </asp:TemplateField>
                   <asp:TemplateField HeaderText="Tracking Type">
                  <ItemTemplate>
                  <asp:DropDownList ID="ddlTrackingType" runat="server" AutoPostBack="false" SelectedValue='<%# Eval("Gtri_TrackingType") %>'   >
                   <asp:ListItem Text="Select..." Value="0" />
                   <asp:ListItem Text="Fed Ex" Value="1" />  
                   <asp:ListItem Text="UPS" Value="2" />  
                   <asp:ListItem Text="Other" Value="3" />                        
                  </asp:DropDownList>
                  <asp:CompareValidator id="CompareValidator1" ControlToValidate="ddlTrackingType" ControlToCompare="txtTrackingNumb" runat="server" >*</asp:CompareValidator>
                  </ItemTemplate>
                  </asp:TemplateField>

C# Code behind: (in button click) also tried the below code in the gridviews row index...still does not work
                 // Validate Control...bind validation controls in a paticular row.
                try
                {
                    if (gvParent.EditIndex == e.Row.RowIndex)
                    {
                        if (txtTrackingNumb != null) //e.Row.RowIndex
                        {
                            //TextBox txtTrackingVal = (TextBox)e.Row.FindControl("txtTrackingNumb");
                            //if (txtTrackingVal != null)
                            //{
                            CompareValidator compareValidator = new CompareValidator();
                            compareValidator.ID = "CompareValidator1";
                            compareValidator.ControlToValidate = "ddlTrackingType";
                            compareValidator.ControlToCompare = "txtTrackingNumb";
                            compareValidator.ErrorMessage = "Required!";
                            compareValidator.SetFocusOnError = true;
                            e.Cells[1].Controls.Add(compareValidator);
                            //}
                        }
                    }
                }
                catch (Exception ex)
                {
                    lblMessage.Text = "An error occurred";
                }

Please help......back is up to a deadline and this is the last pice ....... been working on a solution for the past 3 days
0
newjeep19
Asked:
newjeep19
  • 3
1 Solution
 
MrunalCommented:
First thing un-comment your line
//alert(1);

And i am sure you will not get that alert.

The reason behind of this is:
you have not assigned css class TrackingNo to textbox.

Also your jquery code is nice approach compared with compare validator.
0
 
newjeep19Author Commented:
I solved the issue on my own.  I am using C# code behind
Code:
 foreach (GridViewRow r in gvParent.Rows)
                    {
                        if (r.RowType == DataControlRowType.DataRow)
                        {
                            // Tracing Type validator
                            TextBox txtTrackingNumb = (TextBox)r.FindControl("txtTrackingNumb");
                            DropDownList ddlTrackingType = (DropDownList)r.FindControl("ddlTrackingType");
                            string tracType = String.Empty;
                            if (!String.IsNullOrEmpty(txtTrackingNumb.Text))
                            {
                                tracType = ddlTrackingType.SelectedValue;
                                if (tracType == "0")
                                {
                                    //message: Need to enter in a tracking type (1,2,3) for the tracking
                                    lblMessage.Text = "You must enter in a Tracking Type (FedEx, UPS or Other) for Tracking # :  " + txtTrackingNumb.Text;
                                    lblMessage.ForeColor = System.Drawing.Color.Red;
                                    return;
                                }
                            }
0
 
newjeep19Author Commented:
Found my own solution
0
 
newjeep19Author Commented:
foreach (GridViewRow r in gvParent.Rows)
                    {
                        if (r.RowType == DataControlRowType.DataRow)
                        {
                            // Tracing Type validator
                            TextBox txtTrackingNumb = (TextBox)r.FindControl("txtTrackingNumb");
                            DropDownList ddlTrackingType = (DropDownList)r.FindControl("ddlTrackingType");
                            string tracType = String.Empty;
                            if (!String.IsNullOrEmpty(txtTrackingNumb.Text))
                            {
                                tracType = ddlTrackingType.SelectedValue;
                                if (tracType == "0")
                                {
                                    //message: Need to enter in a tracking type (1,2,3) for the tracking
                                    lblMessage.Text = "You must enter in a Tracking Type (FedEx, UPS or Other) for Tracking # :  " + txtTrackingNumb.Text;
                                    lblMessage.ForeColor = System.Drawing.Color.Red;
                                    return;
                                }
                            }
0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now