locked
Required Field validator in edit item template is not working RRS feed

  • Question

  • User1151703306 posted

    Hi all, I need your help.

    My code below.

    I am using a gridview in asp.net.

    I am trying to add a requiredfieldvalidator to the txtfoo in gridview edit mode.

    But if I put anything in the textbox and click update the message is always the field is required.

    Can you help me ?

                                        <asp:TemplateField HeaderText="Edit" ItemStyle-HorizontalAlign="Center">
    
                                            <ItemTemplate>
                                                <asp:ImageButton ID="imgbtnEdit"
                                                    runat="server"
                                                    CommandName="Edit"
                                                    ImageUrl="/aspnet/img/edit_icon.gif" />
                                            </ItemTemplate>
    
                                            <EditItemTemplate>
                                                <asp:ImageButton ID="imgbtnUpdate"
                                                    runat="server"
                                                    CommandName="Update"
                                                    ImageUrl="/aspnet/img/update.gif"
                                                    ValidationGroup="Validation2" />
                                            </EditItemTemplate>
    
                                        </asp:TemplateField>
    
    
                                        <asp:TemplateField HeaderText="foo">
                                            <ItemTemplate><%#Eval("foo")%></ItemTemplate>
                                            <EditItemTemplate>
                                                <asp:TextBox ID="txtfoo" runat="server" Text='<%#Eval("foo")%>'
                                                    CssClass="pure-u-23-24" />
    
                                                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtfoo"
                                                    SetFocusOnError="true" ErrorMessage="Required" Display="None"
                                                    ValidationGroup="Validation2" CssClass="validation-summary-errors-one"></asp:RequiredFieldValidator>
    
                                            </EditItemTemplate>
                                        </asp:TemplateField>
                                    
                                 ...
    
                                 </asp:GridView>
    
                                <asp:ValidationSummary ID="ValidationSummary1" ValidationGroup="Validation2" runat="server" ShowSummary="false"
                                     ShowMessageBox="true" CssClass="validation-summary-errors" />

    Tuesday, September 10, 2019 2:09 PM

Answers

  • User288213138 posted

    Hi Golia,

    You can try to set breakpoints to debug your code and find what's the problem.

    If that doesn't solve your problem, please post your aspx and aspx.cs code.

    Best regards,

    sam

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, September 23, 2019 11:43 AM

All replies

  • User288213138 posted

    Hi Golia,

    I tested your code and found no problems with what you said. And it works fine.

    The code:

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit">
                    <Columns>
                        <asp:TemplateField HeaderText="Edit" ItemStyle-HorizontalAlign="Center">
                            <ItemTemplate>
                                <asp:ImageButton ID="imgbtnEdit"
                                    runat="server"
                                    CommandName="Edit"
                                    ImageUrl="~/Images/3.jpg" />
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:ImageButton ID="imgbtnUpdate"
                                    runat="server"
                                    CommandName="Update"
                                    ImageUrl="~/Images/3.jpg"
                                    ValidationGroup="Validation2" />
                            </EditItemTemplate>
                        </asp:TemplateField>
    
    
                        <asp:TemplateField HeaderText="foo">
                            <ItemTemplate><%#Eval("foo")%></ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="txtfoo" runat="server" Text='<%#Eval("foo")%>'
                                    CssClass="pure-u-23-24" />
                             <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtfoo"
                                                    SetFocusOnError="true" ErrorMessage="Required"
                                                     CssClass="validation-summary-errors-one"></asp:RequiredFieldValidator>
                            </EditItemTemplate>
                        </asp:TemplateField>
                        <asp:CommandField ShowEditButton="true"/>
                    </Columns>
                </asp:GridView>
    
    protected void Page_Load(object sender, EventArgs e)
            {          
                if (!IsPostBack)
                {
                    BindGrid();
                }
            }
            public void BindGrid()
            {
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                string query = "SELECT * FROM Customer";
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
                    {
                        using (DataTable dt = new DataTable())
                        {
                            sda.Fill(dt);
                            GridView1.DataSource = dt;
                            GridView1.DataBind();
                        }
                    }
                }
            }
    
            protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
            {
                GridView1.EditIndex = e.NewEditIndex;
                BindGrid();
            }
    
            protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {
                GridViewRow row = GridView1.Rows[e.RowIndex];
    
                string foo = (row.FindControl("txtfoo") as TextBox).Text;
                string query = "UPDATE Customer SET foo=@foo ";
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
              
                        cmd.Parameters.AddWithValue("@foo", foo);              
                        cmd.Connection = con;
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }
                GridView1.EditIndex = -1;
                BindGrid();
            }
    
            protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
                GridView1.EditIndex = -1;
                BindGrid();
            }
    
    

    The result:

    Best regards,

    Sam

    Wednesday, September 11, 2019 2:35 AM
  • User1151703306 posted

    Hello Sam, 

    Thank you, but my first question is confusedly written ... I'm sorry ...

    Explanation :

    I have inserted a child GridView (Nested GridView) inside a main GridView.

    This is the tutorial : https://www.aspsnippets.com/Articles/Nested-GridView-Example-in-ASPNet-using-C-and-VBNet.aspx 

    I need edit the values in the child GridView and make them all required, so I associated the RequiredFieldValidator property and the ValidationGroup property for each field to be edited.

    The problem is that once the row of the child GridView has been prepared for the edit, even if I insert the values in the TextBoxes, the system always required them as if the TextBoxes were null or empty.

    I have no idea why he behaves like that and, above all, what I'm doing wrong.

    Child GridView complete code

                   <%--START CHILDGRIDVIEW --%>
                    <asp:TemplateField HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
                        <ItemTemplate>
                            <img alt="" style="cursor: pointer" src="/aspnet/img/plus.png" class="ddl_Class_new" />
                            <asp:Panel ID="pnlOrders" runat="server" Style="display: none">
                                <asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid"
                                    OnRowUpdating="gvOrders_RowUpdating"
                                    OnRowEditing="gvOrders_RowEditing"
                                    OnRowCancelingEdit="gvOrders_RowCancelingEdit">
                                    <Columns>
    
                                        <%--SUBCol 0--%>
                                        <asp:TemplateField HeaderText="" Visible="false">
                                            <ItemTemplate>
                                                <asp:Label ID="lblsID" Text='<%# Eval("sID") %>' runat="server"></asp:Label>
                                            </ItemTemplate>
                                        </asp:TemplateField>
    
                                        <%--SUBCol 1--%>
                                        <asp:TemplateField HeaderText="Edit" ItemStyle-HorizontalAlign="Center">
                                            <ItemTemplate>
                                                <asp:ImageButton ID="imgbtnEdit"
                                                    runat="server"
                                                    CommandName="Edit"
                                                    ImageUrl="/aspnet/img/edit_icon.gif"
                                                    OnClientClick="return confirm('Are sure ?');" />
                                            </ItemTemplate>
    
                                            <EditItemTemplate>
                                                <asp:ImageButton ID="imgbtnUpdate"
                                                    runat="server"
                                                    CommandName="Update"
                                                    ImageUrl="/aspnet/img/update.gif"
                                                    OnClientClick="if(!confirm('Are sure ?')) return;"
                                                    ValidationGroup='<%# Eval("sID")%>'  />
    
                                                <asp:ImageButton ID="imgbtnCancel"
                                                    runat="server"
                                                    CommandName="Cancel"
                                                    ImageUrl="/aspnet/img/cancel.gif"
                                                    OnClientClick="return confirm('Are sure ?');" />
    
                                            </EditItemTemplate>
    
                                        </asp:TemplateField>
    
                                        <%--SUBCol 2--%>
                                        <asp:TemplateField HeaderText="intervention">
                                            <ItemTemplate><%#Eval("intervention")%></ItemTemplate>
                                            <EditItemTemplate>
                                                <asp:TextBox ID="txtintervention" runat="server" Text='<%#Eval("intervention")%>'
                                                    CssClass="pure-u-23-24" />
    
                                                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtintervention"
                                                    SetFocusOnError="true" ErrorMessage="intervention : Required" Display="None"
                                                    ValidationGroup='<%# Eval("sID")%>' CssClass="validation-summary-errors-one"></asp:RequiredFieldValidator>
    
                                            </EditItemTemplate>
                                        </asp:TemplateField>
    
                                        <%--SUBCol 3--%>
                                        <asp:TemplateField HeaderText="workshop">
                                            <ItemTemplate><%#Eval("workshop")%></ItemTemplate>
                                            <EditItemTemplate>
                                                <asp:TextBox ID="txtworkshop" runat="server" Text='<%#Eval("workshop")%>'
                                                    CssClass="pure-u-23-24" />
    
                                                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtworkshop"
                                                    SetFocusOnError="true" ErrorMessage="workshop : Required" Display="None"
                                                    ValidationGroup='<%# Eval("sID")%>'
                                                    CssClass="validation-summary-errors-one"></asp:RequiredFieldValidator>
    
                                            </EditItemTemplate>
                                        </asp:TemplateField>
    
                                        <%--SUBCol 4--%>
                                        <asp:TemplateField HeaderText="sequence">
                                            <ItemTemplate><%#Eval("sequence")%></ItemTemplate>
                                            <EditItemTemplate>
                                                <asp:TextBox ID="txtsequence" runat="server" Text='<%#Eval("sequence")%>'
                                                    CssClass="pure-u-23-24" />
    
                                                <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtsequence"
                                                    SetFocusOnError="true" ErrorMessage="Sequence : Required" Display="None"
                                                    ValidationGroup='<%# Eval("sID")%>'
                                                    CssClass="validation-summary-errors-one"></asp:RequiredFieldValidator>
    
                                            </EditItemTemplate>
                                        </asp:TemplateField>
    
                                        <%--SUBCol 5--%>
                                        <asp:TemplateField HeaderText="Priority">
                                            <ItemTemplate><%#Eval("Priority")%></ItemTemplate>
                                            <EditItemTemplate>
                                                <asp:DropDownList runat="server" ID="ddlPriority" CssClass="pure-u-23-24">
                                                    <asp:ListItem Text="[ === Priority === ]" Value=""></asp:ListItem>
                                                    <asp:ListItem Text="1" Value="1"></asp:ListItem>
                                                    <asp:ListItem Text="2" Value="2"></asp:ListItem>
                                                    <asp:ListItem Text="3" Value="3"></asp:ListItem>
                                                    <asp:ListItem Text="4" Value="4"></asp:ListItem>
                                                    <asp:ListItem Text="5" Value="5"></asp:ListItem>
                                                </asp:DropDownList>
    
                                                <asp:RequiredFieldValidator ID="RequiredFieldValidator" runat="server" ControlToValidate="ddlPriority"
                                                    SetFocusOnError="true" ErrorMessage="Priority : Required" Display="None"
                                                    ValidationGroup='<%# Eval("sID")%>'
                                                    CssClass="validation-summary-errors-one"></asp:RequiredFieldValidator>
    
                                            </EditItemTemplate>
                                        </asp:TemplateField>
    
                                        <%--SUBCol 6--%>
                                        <asp:TemplateField HeaderText="return">
                                            <ItemTemplate><%#Eval("return")%></ItemTemplate>
                                            <EditItemTemplate>
                                                <asp:TextBox ID="txtreturn" runat="server" Text='<%#Eval("return")%>' CssClass="pure-u-23-24" />
    
                                                <asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ControlToValidate="txtreturn"
                                                    SetFocusOnError="true" ErrorMessage="return : Required" Display="None"
                                                    ValidationGroup='<%# Eval("sID")%>'
                                                    CssClass="validation-summary-errors-one"></asp:RequiredFieldValidator>
    
                                            </EditItemTemplate>
                                        </asp:TemplateField>
    
                                    </Columns>
                                </asp:GridView>
                                <asp:ValidationSummary ID="ValidationSummary1" ValidationGroup='<%# Eval("sID")%>'
                                    runat="server" ShowSummary="false" ShowMessageBox="true" CssClass="validation-summary-errors" />
                            </asp:Panel>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <%--END CHILDGRIDVIEW --%>

    Wednesday, September 11, 2019 1:12 PM
  • User288213138 posted

    Hi Golia,

    <ItemTemplate>
                                                <asp:ImageButton ID="imgbtnEdit"
                                                    runat="server"
                                                    CommandName="Edit"
                                                    ImageUrl="/aspnet/img/edit_icon.gif"
                                                    OnClientClick="return confirm('Are sure ?');" />
                                            </ItemTemplate>

    How do you let the Gridview into edit mode? in your code , I didn't find the button that generated Edit.

    By clicking on this imagebutton? 

    please post the code behind, i need it to reproduce your problem.

    Best regards,

    Sam

    Thursday, September 12, 2019 9:29 AM
  • User1151703306 posted

    Hi Sam, thanks for reply.

    This is the button imgbtnUpdate that generated Update on child Gridview.

    In this button I have inserted the ValidationGroup property for each row prepared for the edit and update.

    In this moment I don't have code behind because I have to complete the check of the required fields.

       <EditItemTemplate>
           <asp:ImageButton ID="imgbtnUpdate"
               runat="server"
               CommandName="Update"
               ImageUrl="/aspnet/img/update.gif"
               OnClientClick="if(!confirm('Are sure ?')) return;"
               ValidationGroup='<%# Eval("sID")%>'  />
    
               ....
    
       </EditItemTemplate>
        protected void gvOrders_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            //work in progress
        }



    Thursday, September 12, 2019 10:14 AM
  • User-1716253493 posted

    You can try

    • remove onclientclick
    • and change ValidationGroup='<%# Eval("sID","validationgroup{0}")%>'
    Friday, September 13, 2019 7:16 AM
  • User1151703306 posted

    Hello oned_gk, thanks for help.

    I tried with your suggestion but :

    1.  If I insert the values in the TextBoxes, the system always required them as if the TextBoxes were null or empty;
    2. The DropDownList ddlPriority it's not required even if the selected value is null.

    This is he new  Child GridView complete code with your changes suggested :

           <%--START CHILDGRIDVIEW --%>
            <asp:TemplateField HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
                <ItemTemplate>
                    <img alt="" style="cursor: pointer" src="/aspnet/img/plus.png" class="ddl_Class_new" />
                    <asp:Panel ID="pnlOrders" runat="server" Style="display: none">
                        <asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid"
                            OnRowUpdating="gvOrders_RowUpdating"
                            OnRowEditing="gvOrders_RowEditing"
                            OnRowCancelingEdit="gvOrders_RowCancelingEdit">
                            <Columns>
        
                                <%--SUBCol 0--%>
                                <asp:TemplateField HeaderText="" Visible="false">
                                    <ItemTemplate>
                                        <asp:Label ID="lblsID" Text='<%# Eval("sID") %>' runat="server"></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
        
                                <%--SUBCol 1--%>
                                <asp:TemplateField HeaderText="Edit" ItemStyle-HorizontalAlign="Center">
                                    <ItemTemplate>
                                        <asp:ImageButton ID="imgbtnEdit"
                                            runat="server"
                                            CommandName="Edit"
                                            ImageUrl="/aspnet/img/edit_icon.gif"
                                            OnClientClick="return confirm('Are you sure ?');" />
                                    </ItemTemplate>
        
                                    <EditItemTemplate>
                                        <asp:ImageButton ID="imgbtnUpdate"
                                            runat="server"
                                            CommandName="Update"
                                            ImageUrl="/aspnet/img/update.gif"
                                            ValidationGroup='<%# Eval("sID","validationgroup{0}")%>'  />
        
                                        <asp:ImageButton ID="imgbtnCancel"
                                            runat="server"
                                            CommandName="Cancel"
                                            ImageUrl="/aspnet/img/cancel.gif"
                                            OnClientClick="return confirm('Are you sure ?');" />
        
                                    </EditItemTemplate>
        
                                </asp:TemplateField>
        
                                <%--SUBCol 2--%>
                                <asp:TemplateField HeaderText="intervention">
                                    <ItemTemplate><%#Eval("intervention")%></ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:TextBox ID="txtintervention" runat="server" Text='<%#Eval("intervention")%>'
                                            CssClass="pure-u-23-24" />
        
                                        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtintervention"
                                            SetFocusOnError="true" ErrorMessage="intervention : Required" Display="None"
                                            ValidationGroup='<%# Eval("sID","validationgroup{0}")%>' CssClass="validation-summary-errors-one"></asp:RequiredFieldValidator>
        
                                    </EditItemTemplate>
                                </asp:TemplateField>
        
                                <%--SUBCol 3--%>
                                <asp:TemplateField HeaderText="workshop">
                                    <ItemTemplate><%#Eval("workshop")%></ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:TextBox ID="txtworkshop" runat="server" Text='<%#Eval("workshop")%>'
                                            CssClass="pure-u-23-24" />
        
                                        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtworkshop"
                                            SetFocusOnError="true" ErrorMessage="workshop : Required" Display="None"
                                            ValidationGroup='<%# Eval("sID","validationgroup{0}")%>'
                                            CssClass="validation-summary-errors-one"></asp:RequiredFieldValidator>
        
                                    </EditItemTemplate>
                                </asp:TemplateField>
        
                                <%--SUBCol 4--%>
                                <asp:TemplateField HeaderText="sequence">
                                    <ItemTemplate><%#Eval("sequence")%></ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:TextBox ID="txtsequence" runat="server" Text='<%#Eval("sequence")%>'
                                            CssClass="pure-u-23-24" />
        
                                        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtsequence"
                                            SetFocusOnError="true" ErrorMessage="Sequence : Required" Display="None"
                                            ValidationGroup='<%# Eval("sID","validationgroup{0}")%>'
                                            CssClass="validation-summary-errors-one"></asp:RequiredFieldValidator>
        
                                    </EditItemTemplate>
                                </asp:TemplateField>
        
                                <%--SUBCol 5--%>
                                <asp:TemplateField HeaderText="Priority">
                                    <ItemTemplate><%#Eval("Priority")%></ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:DropDownList runat="server" ID="ddlPriority" CssClass="pure-u-23-24">
                                            <asp:ListItem Text="[ === Priority === ]" Value=""></asp:ListItem>
                                            <asp:ListItem Text="1" Value="1"></asp:ListItem>
                                            <asp:ListItem Text="2" Value="2"></asp:ListItem>
                                            <asp:ListItem Text="3" Value="3"></asp:ListItem>
                                            <asp:ListItem Text="4" Value="4"></asp:ListItem>
                                            <asp:ListItem Text="5" Value="5"></asp:ListItem>
                                        </asp:DropDownList>
        
                                        <asp:RequiredFieldValidator ID="RequiredFieldValidator" runat="server" ControlToValidate="ddlPriority"
                                            SetFocusOnError="true" ErrorMessage="Priority : Required" Display="None"
                                            ValidationGroup='<%# Eval("sID","validationgroup{0}")%>'
                                            CssClass="validation-summary-errors-one"></asp:RequiredFieldValidator>
        
                                    </EditItemTemplate>
                                </asp:TemplateField>
        
                                <%--SUBCol 6--%>
                                <asp:TemplateField HeaderText="return">
                                    <ItemTemplate><%#Eval("return")%></ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:TextBox ID="txtreturn" runat="server" Text='<%#Eval("return")%>' CssClass="pure-u-23-24" />
        
                                        <asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ControlToValidate="txtreturn"
                                            SetFocusOnError="true" ErrorMessage="return : Required" Display="None"
                                            ValidationGroup='<%# Eval("sID","validationgroup{0}")%>'
                                            CssClass="validation-summary-errors-one"></asp:RequiredFieldValidator>
        
                                    </EditItemTemplate>
                                </asp:TemplateField>
        
                            </Columns>
                        </asp:GridView>
                        <asp:ValidationSummary ID="ValidationSummary1" ValidationGroup='<%# Eval("sID","validationgroup{0}")%>'
                            runat="server" ShowSummary="false" ShowMessageBox="true" CssClass="validation-summary-errors" />
                    </asp:Panel>
                </ItemTemplate>
            </asp:TemplateField>
            <%--END CHILDGRIDVIEW --%>

    Friday, September 13, 2019 8:41 AM
  • User288213138 posted

    Hi Golia,

    The reason for RequiredFieldValidator doesn't work is because some problems with your js code.

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $("[src*=plus]").live("click", function () {
            $(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
            $(this).attr("src", "images/minus.png");
        });
        $("[src*=minus]").live("click", function () {
            $(this).attr("src", "images/plus.png");
            $(this).closest("tr").next().remove();
        });
    </script>

    This is your js code for expanding the child Gridview, but when you use the after () method to add $(this).next().html() to tr, the RequiredFieldValidator will not work.

    So I suggest you try other methods to implement a nested Gridview, and i made demo for you:

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand">
                    <Columns>
                        <asp:TemplateField HeaderText="Details">
                            <ItemTemplate>
                                <asp:Button ID="btn_Show" Text="Details" runat="server" CommandName="Details" CommandArgument='<%#Container.DataItemIndex%>' />
                                <asp:Button ID="Cancel" Text="Cancel" runat="server" CommandName="Cancel" CommandArgument='<%#Container.DataItemIndex%>' Visible="false" />
                                <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" OnRowEditing="GridView2_RowEditing" OnRowUpdating="GridView2_RowUpdating">
                                    <Columns>
                                        <asp:TemplateField HeaderText="Edit" ItemStyle-HorizontalAlign="Center">
                                            <ItemTemplate>
                                                Edit:
                                                <asp:ImageButton ID="imgbtnEdit" runat="server" CommandName="Edit" ImageUrl="~/Images/plus.PNG" />
                                            </ItemTemplate>
    
                                            <EditItemTemplate>
                                                Updata:<asp:ImageButton ID="imgbtnUpdate" runat="server" CommandName="Update" ImageUrl="~/Images/plus.PNG" />
                                                Cancle:<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/Images/minus.PNG" />
                                            </EditItemTemplate>
                                        </asp:TemplateField>
                                        <asp:TemplateField HeaderText="Id">
                                            <ItemTemplate>
                                                <asp:Label ID="lblId" Text='<%# Eval("Id") %>' runat="server"></asp:Label>
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                        <asp:TemplateField ItemStyle-Width="100px" HeaderText="Name">
                                            <ItemTemplate>
                                                <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name")%>'></asp:Label>
                                            </ItemTemplate>
                                            <EditItemTemplate>
                                                <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name")%>'></asp:TextBox>
                                           <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName"
                                            SetFocusOnError="true" ErrorMessage="txtName: Required"></asp:RequiredFieldValidator>
    
                                            </EditItemTemplate>
                                        </asp:TemplateField>
                                        <asp:TemplateField ItemStyle-Width="100px" HeaderText="Address">
                                            <ItemTemplate>
                                                <asp:Label ID="lblAddress" runat="server" Text='<%# Eval("Address")%>'></asp:Label>
                                            </ItemTemplate>
                                            <EditItemTemplate>
                                                <asp:TextBox ID="txtAddress" runat="server" Text='<%# Bind("Address")%>'></asp:TextBox>
                                            </EditItemTemplate>
                                        </asp:TemplateField>
    
                                    </Columns>
                                </asp:GridView>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Department_Id">
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Dept_Id") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%# Bind("Dept_Id") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Department_Name">
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Dept_Name") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label2" runat="server" Text='<%# Bind("Dept_Name") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>                  
                    </Columns>
                </asp:GridView>
    
    
    string connStr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;                      
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindGrid();
                }
            }
            protected void BindGrid()
            {                 
                string query = "SELECT * FROM Departments";
                using (SqlConnection con = new SqlConnection(connStr))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
                    {
                        using (DataTable dt = new DataTable())
                        {
                            sda.Fill(dt);
                            GridView1.DataSource = dt;
                            GridView1.DataBind();
                        }
                    }
                }
            }
            protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
            {
                int rowindex = Convert.ToInt32(e.CommandArgument.ToString());
                GridView g2 = (GridView)GridView1.Rows[rowindex].FindControl("GridView2");
                Label lbl = (Label)GridView1.Rows[rowindex].FindControl("Label2");
                GridView1.Rows[rowindex].FindControl("Cancel").Visible = false;
                if (e.CommandName == "Details")
                {
                    GridView1.Rows[rowindex].FindControl("Cancel").Visible = true;
                    GridView1.Rows[rowindex].FindControl("btn_Show").Visible = false;       
                    string query = "SELECT * FROM Employees";
                    using (SqlConnection con = new SqlConnection(connStr))
                    {
                        using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
                        {
                            using (DataTable dt = new DataTable())
                            {
                                sda.Fill(dt);
                                g2.DataSource = dt;
                                g2.DataBind();
                            }
                        }
                    }
                    g2.Visible = true;
                }
                else
                {
                    g2.Visible = false;
                    GridView1.Rows[rowindex].FindControl("btn_Show").Visible = true;
                }
            }
    
            protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
            {
    
            }
    
            protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {
                
            }

    The result:

    Best regards,

    Sam
     

    Tuesday, September 17, 2019 8:23 AM
  • User1151703306 posted

    Hello samwu, thank you for reply.

    I have tried your suggestion but your code has multiple problems :

    1. For edit row I need click twice on the imgbtnEdit;
    2. The Button "Cancel" not working;
    3. Can't switch from one row edit to the next row;
    4. The ImageButton "imgbtnCancel"  not working;
    5. etc etc
    Wednesday, September 18, 2019 12:06 PM
  • User288213138 posted

    Hi Golia,

    The demo I made is just to prove that this method is feasible. Only did some of the functions

    Golia

    For edit row I need click twice on the imgbtnEdit;

    You need to click the button twice because there's nothing to set in the GridView2_RowEditing event. below code will solve this problem.

    protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
            {
                GridView g = (GridView)sender;
                g.EditIndex = e.NewEditIndex;
                string query = "SELECT * FROM Employees";
                using (SqlConnection con = new SqlConnection(connStr))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
                    {
                        using (DataTable dt = new DataTable())
                        {
                            sda.Fill(dt);
                            g.DataSource = dt;
                            g.DataBind();
                        }
                    }
                }
            }

    Golia

    The Button "Cancel" not working;

    The Button "Cancel" not working that because there's nothing to set in the GridView2_RowCancelingEdit.

    Golia

    Can't switch from one row edit to the next row;

    How do you want to switch to the next row edit?

    Golia

    The ImageButton "imgbtnCancel"  not working;

    That because not set GridView1_RowCancelingEdit event.

    I modified my code for you. I hope you can improve the code yourself.

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" OnRowCancelingEdit="GridView1_RowCancelingEdit">
                    <Columns>
                        <asp:TemplateField HeaderText="Details">
                            <ItemTemplate>
                                <asp:Button ID="btn_Show" Text="Details" runat="server" CommandName="Details" CommandArgument='<%#Container.DataItemIndex%>' />
                                <asp:Button ID="Cancel" Text="Cancel" runat="server" CommandName="Cancel" CommandArgument='<%#Container.DataItemIndex%>' Visible="false" />
                                <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" OnRowEditing="GridView2_RowEditing" OnRowCancelingEdit="GridView2_RowCancelingEdit">
                                    <Columns>
                                        <asp:TemplateField HeaderText="Edit" ItemStyle-HorizontalAlign="Center">
                                            <ItemTemplate>
                                                Edit:
                                                <asp:ImageButton ID="imgbtnEdit" runat="server" CommandName="Edit" ImageUrl="~/Images/plus.PNG" />
                                            </ItemTemplate>
    
                                            <EditItemTemplate>
                                                Updata:<asp:ImageButton ID="imgbtnUpdate" runat="server" CommandName="Update" ImageUrl="~/Images/plus.PNG" />
                                                Cancle:<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/Images/minus.PNG" />
                                            </EditItemTemplate>
                                        </asp:TemplateField>
                                        <asp:TemplateField HeaderText="Id">
                                            <ItemTemplate>
                                                <asp:Label ID="lblId" Text='<%# Eval("Id") %>' runat="server"></asp:Label>
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                        <asp:TemplateField ItemStyle-Width="100px" HeaderText="Name">
                                            <ItemTemplate>
                                                <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name")%>'></asp:Label>
                                            </ItemTemplate>
                                            <EditItemTemplate>
                                                <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name")%>'></asp:TextBox>
                                           <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName"
                                            SetFocusOnError="true" ErrorMessage="txtName : Required"></asp:RequiredFieldValidator>
    
                                            </EditItemTemplate>
                                        </asp:TemplateField>
                                        <asp:TemplateField ItemStyle-Width="100px" HeaderText="Address">
                                            <ItemTemplate>
                                                <asp:Label ID="lblAddress" runat="server" Text='<%# Eval("Address")%>'></asp:Label>
                                            </ItemTemplate>
                                            <EditItemTemplate>
                                                <asp:TextBox ID="txtAddress" runat="server" Text='<%# Bind("Address")%>'></asp:TextBox>
                                            </EditItemTemplate>
                                        </asp:TemplateField>
    
                                    </Columns>
                                </asp:GridView>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Department_Id">
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Dept_Id") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%# Bind("Dept_Id") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Department_Name">
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Dept_Name") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label2" runat="server" Text='<%# Bind("Dept_Name") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>                  
                    </Columns>
                </asp:GridView>
    
    string connStr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;                      
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    GridView1.DataSource = GetData("select * from Departments");
                    GridView1.DataBind();
                }
            }    
            private static DataTable GetData(string query)
            {
                string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(strConnString))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.CommandText = query;
                        using (SqlDataAdapter sda = new SqlDataAdapter())
                        {
                            cmd.Connection = con;
                            sda.SelectCommand = cmd;
                            using (DataSet ds = new DataSet())
                            {
                                DataTable dt = new DataTable();
                                sda.Fill(dt);
                                return dt;
                            }
                        }
                    }
                }
            }
            protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
            {
                int rowindex = Convert.ToInt32(e.CommandArgument.ToString());
                GridView g2 = (GridView)GridView1.Rows[rowindex].FindControl("GridView2");
                Label lbl = (Label)GridView1.Rows[rowindex].FindControl("Label2");
                GridView1.Rows[rowindex].FindControl("Cancel").Visible = false;
                if (e.CommandName == "Details")
                {
                    GridView1.Rows[rowindex].FindControl("Cancel").Visible = true;
                    GridView1.Rows[rowindex].FindControl("btn_Show").Visible = false;              
                    g2.DataSource = GetData("select * from Employees");
                    g2.DataBind();
                    g2.Visible = true;
                }
                else
                {
                    g2.Visible = false;
                    GridView1.Rows[rowindex].FindControl("btn_Show").Visible = true;
                }
            }
    
            protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
            {
                GridView g2 = (GridView)sender;
                g2.EditIndex = e.NewEditIndex;
                g2.DataSource = GetData("select * from Employees");
                g2.DataBind();
            }
    
            protected void GridView2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
                GridView g2 = (GridView)sender;
                g2.EditIndex = -1;
                g2.DataSource = GetData("select * from Employees");
                g2.DataBind();                
            }
    
    
            protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
                GridView1.EditIndex = -1;
                GridView1.DataSource = GetData("select * from Departments");
                GridView1.DataBind();
            }

    The result:

    Best regards,

    Sam

    Thursday, September 19, 2019 10:59 AM
  • User1151703306 posted

    Hello samwu, thank you so much for reply.

    I really appreciated your help. smile

    I have now only this problem : is when I change edit row for new edit row on main GridView, the last row remains open on child GridView and not closing for editing only the new row.

    Thursday, September 19, 2019 11:37 AM
  • User288213138 posted

    Hi Golia,

    is when I change edit row for new edit row on main GridView, the last row remains open on child GridView and not closing for editing only the new row.

    I not quite understand what you mean. Could you describe your question in detail again?

    Or you can cut your question into a image.

    Best regards,

    Sam

    Thursday, September 19, 2019 11:44 AM
  • User1151703306 posted

    samwu

    Hi Golia,

    Golia

    is when I change edit row for new edit row on main GridView, the last row remains open on child GridView and not closing for editing only the new row.

    I not quite understand what you mean. Could you describe your question in detail again?

    Or you can cut your question into a image.

    Best regards,

    Sam

    Okay, this is an example.

    I need edit the row number one on my GV1 :

    And if tried edit the row number two on my GV1 :

    The row number one not closed and I have on GV1 two rows with edit ... instead the only the last one row selected for edit ....

    Thursday, September 19, 2019 11:59 AM
  • User288213138 posted

    Hi Golia,

    The row number one not closed and I have on GV1 two rows with edit

    Do you mean Gv1 multi-row is in edit state?but i try it in my code, its works fine:

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand"
    OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowEditing="GridView1_RowEditing"> <Columns> <asp:CommandField ButtonType="Link" ShowEditButton="true" /> <asp:TemplateField HeaderText="Details"> <ItemTemplate> <asp:Button ID="btn_Show" Text="Details" runat="server" CommandName="Details" CommandArgument='<%#Container.DataItemIndex%>' /> <asp:Button ID="Cancel" Text="Cancel" runat="server" CommandName="Cancel" CommandArgument='<%#Container.DataItemIndex%>' Visible="false" /> <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" OnRowEditing="GridView2_RowEditing" OnRowCancelingEdit="GridView2_RowCancelingEdit"> <Columns> <asp:TemplateField HeaderText="Edit" ItemStyle-HorizontalAlign="Center"> <ItemTemplate> Edit: <asp:ImageButton ID="imgbtnEdit" runat="server" CommandName="Edit" ImageUrl="~/Images/plus.PNG" /> </ItemTemplate> <EditItemTemplate> Updata:<asp:ImageButton ID="imgbtnUpdate" runat="server" CommandName="Update" ImageUrl="~/Images/plus.PNG" /> Cancle:<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/Images/minus.PNG" /> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Id"> <ItemTemplate> <asp:Label ID="lblId" Text='<%# Eval("Id") %>' runat="server"></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField ItemStyle-Width="100px" HeaderText="Name"> <ItemTemplate> <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name")%>'></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name")%>'></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName" SetFocusOnError="true" ErrorMessage="txtName : Required"></asp:RequiredFieldValidator> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField ItemStyle-Width="100px" HeaderText="Address"> <ItemTemplate> <asp:Label ID="lblAddress" runat="server" Text='<%# Eval("Address")%>'></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtAddress" runat="server" Text='<%# Bind("Address")%>'></asp:TextBox> </EditItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Department_Id"> <EditItemTemplate> <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Dept_Id") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("Dept_Id") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Department_Name"> <EditItemTemplate> <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Dept_Name") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label2" runat="server" Text='<%# Bind("Dept_Name") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> string connStr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { GridView1.DataSource = GetData("select * from Departments"); GridView1.DataBind(); } } private static DataTable GetData(string query) { string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(strConnString)) { using (SqlCommand cmd = new SqlCommand()) { cmd.CommandText = query; using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.Connection = con; sda.SelectCommand = cmd; using (DataSet ds = new DataSet()) { DataTable dt = new DataTable(); sda.Fill(dt); return dt; } } } } } protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { int rowindex = Convert.ToInt32(e.CommandArgument.ToString()); GridView g2 = (GridView)GridView1.Rows[rowindex].FindControl("GridView2"); Label lbl = (Label)GridView1.Rows[rowindex].FindControl("Label2"); GridView1.Rows[rowindex].FindControl("Cancel").Visible = false; if (e.CommandName == "Details") { GridView1.Rows[rowindex].FindControl("Cancel").Visible = true; GridView1.Rows[rowindex].FindControl("btn_Show").Visible = false; g2.DataSource = GetData("select * from Employees"); g2.DataBind(); g2.Visible = true; } else { g2.Visible = false; GridView1.Rows[rowindex].FindControl("btn_Show").Visible = true; } } protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e) { GridView g2 = (GridView)sender; g2.EditIndex = e.NewEditIndex; g2.DataSource = GetData("select * from Employees"); g2.DataBind(); } protected void GridView2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView g2 = (GridView)sender; g2.EditIndex = -1; g2.DataSource = GetData("select * from Employees"); g2.DataBind(); } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { //GridView1.EditIndex = -1; //GridView1.DataSource = GetData("select * from Departments"); //GridView1.DataBind(); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView gv2 = (GridView)GridView1.Rows[e.NewEditIndex].FindControl("GridView2"); gv2.EditIndex = -1; GridView1.EditIndex = e.NewEditIndex; GridView1.DataSource = GetData("select * from Departments"); GridView1.DataBind(); }

    Best regards,

    Sam

    Friday, September 20, 2019 9:54 AM
  • User1151703306 posted

    samwu

    Do you mean Gv1 multi-row is in edit state?but i try it in my code, its works fine:

    I see, but not working in my case... 

    Gv1 multi-row is in edit state...

        protected void gv1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView gv2 = (GridView)gv1.Rows[e.NewEditIndex].FindControl("GridView2");
            gv2.EditIndex = -1;
            gv1.EditIndex = e.NewEditIndex;
            BindData();        
        }

    Friday, September 20, 2019 10:17 AM
  • User288213138 posted

    Hi Golia,

    You can try to set breakpoints to debug your code and find what's the problem.

    If that doesn't solve your problem, please post your aspx and aspx.cs code.

    Best regards,

    sam

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, September 23, 2019 11:43 AM