locked
Editable Child Gridview RRS feed

  • Question

  • User-1499457942 posted

    Hi

      how to create nested gridview and inner gridview with crud functionality

    Thanks

    Sunday, November 11, 2018 5:00 AM

All replies

  • User-893317190 posted

    Hi JagjitSingh,

    You could bind your child gridview's data in the parent gridview's  OnRowDataBound event and realize rud in your child gridview's OnRowEditing OnRowDeleting  OnRowUpdating event.

    For createing, you could add a dropdown list to let the user choose which nested gridview to  create data for.

    For example, I have three child gridview, the first , the second, the thrid. You could add a dropdownlist to let the user to choose which child gridview to create data for.

    In your code behind , you could get the selected value and insert into your  database.

    Below is my code .I have two tables , employee and department, one department have many employees.

     <form id="form1" runat="server">
            <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="false">
    
                <Columns>
                    <asp:BoundField DataField="department_name"  HeaderText="department_name"  />
                    <asp:TemplateField HeaderText="employees">
                        <ItemTemplate>
                            <asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("id") %>' /> <!--store the id of department-->
                            <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" ShowHeader="false" DataKeyNames="id" AutoGenerateDeleteButton="true" AutoGenerateEditButton="true" OnRowEditing="GridView2_RowEditing" OnRowDeleting="GridView2_RowDeleting" OnRowUpdating="GridView2_RowUpdating" 
                                 OnRowCancelingEdit="GridView2_RowCancelingEdit">
                               <Columns>
                                   <asp:BoundField DataField="name" />
                                   <asp:BoundField DataField="salary" />
                               </Columns>
                            </asp:GridView>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
    
            </asp:GridView>
            <asp:Label ID="Label1" runat="server" Text="name"></asp:Label>&nbsp;<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <br />
            <asp:Label ID="Label2" runat="server" Text="salary"></asp:Label><asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            <br />
            department<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="department_name" DataValueField="id"></asp:DropDownList><asp:Button ID="create" runat="server" Text="create" OnClick="create_Click" />
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:EntityDb %>" SelectCommand="SELECT [id], [department_name] FROM [department]"></asp:SqlDataSource>
        </form>

    Code behind.

     public partial class childgrid : System.Web.UI.Page
        {
            private static string constr = ConfigurationManager.ConnectionStrings["EntityDb"].ConnectionString;
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack) {
                    using (SqlDataAdapter adapter = new SqlDataAdapter("select * from department", constr))
                    {
    
                        
                        DataTable table = new DataTable();
                        adapter.Fill(table);
                        GridView1.DataSource = table;
                        GridView1.DataBind();
                    }
                }
            }
    
            protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
    
                //bind child gridview's data
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    DataRowView rowView = e.Row.DataItem as DataRowView;
                    int department_id = Convert.ToInt32(rowView["id"]);
                    GridView view = e.Row.FindControl("GridView2") as GridView;
                    using (SqlDataAdapter adapter = new SqlDataAdapter("select * from employee where department_id=@did", constr))
                    {
    
                        adapter.SelectCommand.Parameters.AddWithValue("did", department_id);
                        DataTable table = new DataTable();
                        adapter.Fill(table);
                        view.DataSource = table;
                        view.DataBind();
                    }
                }
               
            }
    
            private void BindChild(GridView child) 
            {
                using (SqlDataAdapter adapter = new SqlDataAdapter("select * from employee where department_id=@did", constr))
                {
                    // get the stored departmentid from the hiddenfield
                    HiddenField field = child.NamingContainer.FindControl("HiddenField1") as HiddenField;
                    string department_id = field.Value;
                    adapter.SelectCommand.Parameters.AddWithValue("did", department_id);
                    DataTable table = new DataTable();
                    adapter.Fill(table);
                    child.DataSource = table;
                    child.DataBind();
                }
            }
    
            protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
            {
                GridView child = (GridView)sender;
                child.EditIndex = e.NewEditIndex;
                BindChild(child);
            }
    
            protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
            {
                GridView child = (GridView)sender;
    
               int id= (int)child.DataKeys[e.RowIndex][0];
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand com = new SqlCommand("delete from employee where id=@id", con))
                    {
                  
                        com.Parameters.AddWithValue("id", id);
                        con.Open();
                        com.ExecuteNonQuery();
                    }
                }
                BindChild(child);
    
            }
    
            protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {
    
                GridView child = (GridView)sender;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand com = new SqlCommand("update employee set name=@name,salary=@salary where id=@id", con))
                    {
                        com.Parameters.AddWithValue("name", e.NewValues["name"]);
                        com.Parameters.AddWithValue("salary", e.NewValues["salary"]);
                        com.Parameters.AddWithValue("id",child.DataKeys[ e.RowIndex]["id"]);
                        con.Open();
                        com.ExecuteNonQuery();
                    }
                }
                child.EditIndex = -1;
                BindChild(child);
            }
    
            protected void GridView2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
                GridView child = (GridView)sender;
                child.EditIndex = -1;
                BindChild(child);
            }
    
            protected void create_Click(object sender, EventArgs e)
            {
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand com = new SqlCommand("insert into employee (name,salary,department_id) values(@name,@salary,@did)", con))
                    {
                        com.Parameters.AddWithValue("name", TextBox1.Text);
                        com.Parameters.AddWithValue("salary", TextBox2.Text);
                        com.Parameters.AddWithValue("did", DropDownList1.SelectedValue);
                        TextBox1.Text = "";
                        TextBox2.Text = "";
                        DropDownList1.SelectedValue = DropDownList1.Items[0].Value;
                        con.Open();
                        com.ExecuteNonQuery();
    
                        //rebind the parent gridview to show the newly inserted data
                        using (SqlDataAdapter adapter = new SqlDataAdapter("select * from department", constr))
                        {
    
    
                            DataTable table = new DataTable();
                            adapter.Fill(table);
                            GridView1.DataSource = table;
                            GridView1.DataBind();
                        }
                    }
                }
            }

    The result.

    Best regards,

    Ackerly Xu

    Monday, November 12, 2018 5:41 AM