locked
Gridview Required Field Validator does not work/trigger RRS feed

  • Question

  • User2142845853 posted

    In a Gridview control in the footer, am using that row to add new data for the INSERT function.  But there needs to be validation even if done manually Id like to see examples of how.

    But in the code,

       <FooterTemplate>
            <asp:TextBox ID="TextBox15" runat="server" Width="140px"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ValidationGroup="TimeSlot" runat="server"
                            ErrorMessage="Date is a Required Field"
                            ControlToValidate="TextBox15"
                            Text="*"></asp:RequiredFieldValidator>
       </FooterTemplate>

    I tried moving the VALIDATIONGROUP= around, doesnt work any way.  When clicking submit, it throws an VS debug exception

    An exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll but was not handled in user code
     
    Additional information: Conversion from string "" to type 'Date' is not valid.
    This is directed at name3
                Dim name1 As String = (CType(GridView1.FooterRow.FindControl("TextBox21"), TextBox)).Text
                Dim name2 As String = (CType(GridView1.FooterRow.FindControl("TextBox22"), TextBox)).Text
                Dim name3 As DateTime = (CType(GridView1.FooterRow.FindControl("TextBox15"), TextBox)).Text
                Dim name4 As Double = (CType(GridView1.FooterRow.FindControl("TextBox23"), TextBox)).Text
                Dim name5 As Double = (CType(GridView1.FooterRow.FindControl("TextBox24"), TextBox)).Text
                Dim name6 As String = (CType(GridView1.FooterRow.FindControl("TextBox25"), TextBox)).Text
                Dim name7 As String = (CType(GridView1.FooterRow.FindControl("TextBox26"), TextBox)).Text
                Dim name8 As String = (CType(GridView1.FooterRow.FindControl("TextBox27"), TextBox)).Text
                Dim name9 As String = (CType(GridView1.FooterRow.FindControl("TextBox28"), TextBox)).Text
                Dim name10 As Double = (CType(GridView1.FooterRow.FindControl("TextBox16"), TextBox)).Text
                Dim name11 As String = (CType(GridView1.FooterRow.FindControl("TextBox17"), TextBox)).Text
                Dim name12 As Double = (CType(GridView1.FooterRow.FindControl("TextBox18"), TextBox)).Text
                Dim name13 As String = (CType(GridView1.FooterRow.FindControl("TextBox19"), TextBox)).Text
                Dim name14 As String = (CType(GridView1.FooterRow.FindControl("TextBox20"), TextBox)).Text
                AstrDataAccessLayer.InsertASTRrc(name1, name2, name3, name4, name5, name6, name7, name8, name9, name10, name11, name12, name13, name14)
                BindGridViewData()
            End If
        End Sub
    What is a working way to use validation on web inputs?  If the VS controls dont work, whats a manual way?
    The Required Validator was added by going into Grid design view, smart tag, Edit Template, selecting the column/footer then on the textbox adding the toolbox item called RequiredFieldValidator under Validation.  It also caused the textbox to be MIS-aligned and raised up higher than all the other textboxes.  Why does the item that isnt shown affecting the page layout.  there is no validation taking place, so it tries to submit and it fails

    Thursday, January 30, 2020 8:01 PM

Answers

  • User665608656 posted

    Hi rogersbr,

    If you want to trigger the validation of the RequiredFieldValidator through the current LinkButton, you need to add the property ValidationGroup to the LinkButton, and its value is the same as the ValidationGroup of the RequiredFieldValidator.

    Then add Page.IsValid validation to your RowCommand event or OnClick event, so that you can ensure that you are executing the insert method to determine whether the validation passes.

    Here is an example based on your code:

      <form id="form1" runat="server">
            <div>
                <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter="true"
                    OnRowCommand="GridView1_RowCommand">
                    <Columns>
                        <asp:TemplateField HeaderText="ID">
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%#Eval("UID") %>'></asp:Label>
                            </ItemTemplate>
                            <FooterTemplate>
                                <asp:TextBox ID="TextBox15" runat="server" Width="140px"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ValidationGroup="TimeSlot" runat="server"
                                    ErrorMessage="Date is a Required Field"
                                    ControlToValidate="TextBox15"
                                    Text="*"></asp:RequiredFieldValidator>
                            </FooterTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Name">
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%#Eval("UName") %>'></asp:Label>
                            </ItemTemplate>
                            <FooterTemplate>
                                <asp:TextBox ID="TextBox16" runat="server" Width="140px"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" ValidationGroup="TimeSlot" runat="server"
                                    ErrorMessage="Date is a Required Field"
                                    ControlToValidate="TextBox16"
                                    Text="*"></asp:RequiredFieldValidator>
                                <asp:LinkButton ID="lblInsert" CommandArgument='<%# Eval("Insert") %>'
                                    CommandName="InsertRow" ForeColor="blue" runat="server" ValidationGroup="TimeSlot">Add ASTR</asp:LinkButton>
                            </FooterTemplate>
                        </asp:TemplateField>
    
                    </Columns>
                </asp:GridView>
            </div>
        </form>
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindData4Grid();
                }
               
            }
    
            private void BindData4Grid()
            {
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ResumeInfoConnectionString"].ConnectionString))
                {
                    conn.Open();
                    string sql = "select UID,UName,UDate,USalary,UAge from NewUsers";
                    SqlDataAdapter ad = new SqlDataAdapter(sql, conn);
                    DataSet ds = new DataSet();
                    ad.Fill(ds, "NewUsers");
                    GridView1.DataSource = ds;
                    GridView1.DataBind();
                }
            }
    
    
            protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
            {
                if (e.CommandName == "InsertRow" && Page.IsValid)
                {
                    TextBox txtnewid = (TextBox)((GridView)sender).FooterRow.FindControl("TextBox15");
                    TextBox txtnewName = (TextBox)((GridView)sender).FooterRow.FindControl("TextBox16");
                    using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ResumeInfoConnectionString"].ConnectionString))
                    using (SqlCommand cmd = new SqlCommand("insert into NewUsers (UID,UName) values (@UID,@UName)", cn))
                    { 
                        cmd.Parameters.Add("@UID", SqlDbType.Int).Value = Convert.ToInt32(txtnewid.Text.ToString());
                        cmd.Parameters.Add("@UName", SqlDbType.NVarChar, 50).Value = txtnewName.Text.ToString(); 
                        cn.Open();
                        cmd.ExecuteNonQuery();
                        cn.Close();
                    }
                    BindData4Grid();
                }
            }

    Here i the result of this work demo:

    You can also refer to this link :

    Step 3: Customizing the Footer Row

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 31, 2020 8:38 AM

All replies

  • User409696431 posted

    What does your Submit button look like?  If you want to validate that textbox (and any other controls with validators with the same ValidationGroup), it should look something like

    <asp:Button ID="btnSend" runat="server" onclick="btnSend_Click" Text="Submit" ValidationGroup="TimeSlot" CausesValidation="true"/>

    The error you mention is not related to validation not working.  It points out that whatever is in that textbox is not being converted to a datetime.

    Friday, January 31, 2020 12:24 AM
  • User2142845853 posted
    <FooterTemplate>
          <asp:LinkButton ID="lblInsert" CommandArgument='<%# Eval("Insert") %>' CommandName="InsertRow" ForeColor="blue" runat="server">Add ASTR</asp:LinkButton>
     </FooterTemplate>

    Here is the Submit on the JS side, clicked with all null/empty values. Needs to trap not having a value.  Isnt that the validation codes purpose

      

    Friday, January 31, 2020 2:29 AM
  • User665608656 posted

    Hi rogersbr,

    If you want to trigger the validation of the RequiredFieldValidator through the current LinkButton, you need to add the property ValidationGroup to the LinkButton, and its value is the same as the ValidationGroup of the RequiredFieldValidator.

    Then add Page.IsValid validation to your RowCommand event or OnClick event, so that you can ensure that you are executing the insert method to determine whether the validation passes.

    Here is an example based on your code:

      <form id="form1" runat="server">
            <div>
                <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter="true"
                    OnRowCommand="GridView1_RowCommand">
                    <Columns>
                        <asp:TemplateField HeaderText="ID">
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%#Eval("UID") %>'></asp:Label>
                            </ItemTemplate>
                            <FooterTemplate>
                                <asp:TextBox ID="TextBox15" runat="server" Width="140px"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ValidationGroup="TimeSlot" runat="server"
                                    ErrorMessage="Date is a Required Field"
                                    ControlToValidate="TextBox15"
                                    Text="*"></asp:RequiredFieldValidator>
                            </FooterTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Name">
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%#Eval("UName") %>'></asp:Label>
                            </ItemTemplate>
                            <FooterTemplate>
                                <asp:TextBox ID="TextBox16" runat="server" Width="140px"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" ValidationGroup="TimeSlot" runat="server"
                                    ErrorMessage="Date is a Required Field"
                                    ControlToValidate="TextBox16"
                                    Text="*"></asp:RequiredFieldValidator>
                                <asp:LinkButton ID="lblInsert" CommandArgument='<%# Eval("Insert") %>'
                                    CommandName="InsertRow" ForeColor="blue" runat="server" ValidationGroup="TimeSlot">Add ASTR</asp:LinkButton>
                            </FooterTemplate>
                        </asp:TemplateField>
    
                    </Columns>
                </asp:GridView>
            </div>
        </form>
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindData4Grid();
                }
               
            }
    
            private void BindData4Grid()
            {
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ResumeInfoConnectionString"].ConnectionString))
                {
                    conn.Open();
                    string sql = "select UID,UName,UDate,USalary,UAge from NewUsers";
                    SqlDataAdapter ad = new SqlDataAdapter(sql, conn);
                    DataSet ds = new DataSet();
                    ad.Fill(ds, "NewUsers");
                    GridView1.DataSource = ds;
                    GridView1.DataBind();
                }
            }
    
    
            protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
            {
                if (e.CommandName == "InsertRow" && Page.IsValid)
                {
                    TextBox txtnewid = (TextBox)((GridView)sender).FooterRow.FindControl("TextBox15");
                    TextBox txtnewName = (TextBox)((GridView)sender).FooterRow.FindControl("TextBox16");
                    using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ResumeInfoConnectionString"].ConnectionString))
                    using (SqlCommand cmd = new SqlCommand("insert into NewUsers (UID,UName) values (@UID,@UName)", cn))
                    { 
                        cmd.Parameters.Add("@UID", SqlDbType.Int).Value = Convert.ToInt32(txtnewid.Text.ToString());
                        cmd.Parameters.Add("@UName", SqlDbType.NVarChar, 50).Value = txtnewName.Text.ToString(); 
                        cn.Open();
                        cmd.ExecuteNonQuery();
                        cn.Close();
                    }
                    BindData4Grid();
                }
            }

    Here i the result of this work demo:

    You can also refer to this link :

    Step 3: Customizing the Footer Row

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 31, 2020 8:38 AM
  • User2142845853 posted

    Thank you, but in my project it will not run. 

    error Additional information: Page.IsValid cannot be called before validation has taken place. It should be queried in the event handler for a control that has CausesValidation=True and initiated the postback, or after a call to Page.Validate.

    its all there, and had to ADD "causesvalidation = true" to the Textbox15.  

    Friday, January 31, 2020 6:44 PM
  • User2142845853 posted

    Yongqing Yu

    Hi rogersbr,

    If you want to trigger the validation of the RequiredFieldValidator through the current LinkButton, you need to add the property ValidationGroup to the LinkButton, and its value is the same as the ValidationGroup of the RequiredFieldValidator.

    Then add Page.IsValid validation to your RowCommand event or OnClick event, so that you can ensure that you are executing the insert method to determine whether the validation passes.

    Here is an example based on your code:

      <form id="form1" runat="server">
            <div>
                <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter="true"
                    OnRowCommand="GridView1_RowCommand">
                    <Columns>
                        <asp:TemplateField HeaderText="ID">
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%#Eval("UID") %>'></asp:Label>
                            </ItemTemplate>
                            <FooterTemplate>
                                <asp:TextBox ID="TextBox15" runat="server" Width="140px"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ValidationGroup="TimeSlot" runat="server"
                                    ErrorMessage="Date is a Required Field"
                                    ControlToValidate="TextBox15"
                                    Text="*"></asp:RequiredFieldValidator>
                            </FooterTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Name">
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%#Eval("UName") %>'></asp:Label>
                            </ItemTemplate>
                            <FooterTemplate>
                                <asp:TextBox ID="TextBox16" runat="server" Width="140px"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" ValidationGroup="TimeSlot" runat="server"
                                    ErrorMessage="Date is a Required Field"
                                    ControlToValidate="TextBox16"
                                    Text="*"></asp:RequiredFieldValidator>
                                <asp:LinkButton ID="lblInsert" CommandArgument='<%# Eval("Insert") %>'
                                    CommandName="InsertRow" ForeColor="blue" runat="server" ValidationGroup="TimeSlot">Add ASTR</asp:LinkButton>
                            </FooterTemplate>
                        </asp:TemplateField>
    
                    </Columns>
                </asp:GridView>
            </div>
        </form>
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindData4Grid();
                }
               
            }
    
            private void BindData4Grid()
            {
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ResumeInfoConnectionString"].ConnectionString))
                {
                    conn.Open();
                    string sql = "select UID,UName,UDate,USalary,UAge from NewUsers";
                    SqlDataAdapter ad = new SqlDataAdapter(sql, conn);
                    DataSet ds = new DataSet();
                    ad.Fill(ds, "NewUsers");
                    GridView1.DataSource = ds;
                    GridView1.DataBind();
                }
            }
    
    
            protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
            {
                if (e.CommandName == "InsertRow" && Page.IsValid)
                {
                    TextBox txtnewid = (TextBox)((GridView)sender).FooterRow.FindControl("TextBox15");
                    TextBox txtnewName = (TextBox)((GridView)sender).FooterRow.FindControl("TextBox16");
                    using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ResumeInfoConnectionString"].ConnectionString))
                    using (SqlCommand cmd = new SqlCommand("insert into NewUsers (UID,UName) values (@UID,@UName)", cn))
                    { 
                        cmd.Parameters.Add("@UID", SqlDbType.Int).Value = Convert.ToInt32(txtnewid.Text.ToString());
                        cmd.Parameters.Add("@UName", SqlDbType.NVarChar, 50).Value = txtnewName.Text.ToString(); 
                        cn.Open();
                        cmd.ExecuteNonQuery();
                        cn.Close();
                    }
                    BindData4Grid();
                }
            }

    Here i the result of this work demo:

    You can also refer to this link :

    Step 3: Customizing the Footer Row

    Best Regards,

    YongQing.

    put  CausesValidation = true in the textcontrol html,  in the If (not postback) I call the Page.Validate(), then in the method If(Page.IsValid) what is the ELSE code?

    if page not valid, it just returns.  works after requesting validation, 

    Saturday, February 1, 2020 2:35 AM