locked
Adding Dynamic Rows To GridView with Jquery without Postback RRS feed

Answers

  • User-707554951 posted

    Hi Ashraf007

    Working code as below:

     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
    <script type = "text/javascript">
        $(function () {
            var gridView = $("[id*=Gridview1]");
            var row = gridView.find("tr").eq(1).clone();
            $("[id*=btnAdd]").click(function () {
                //Reference the first row.
                var preindex = $(this).parent().parent().prev().find("td").eq(0).html();
    
                $("<tr>" + row.html() + "</tr>").insertBefore(gridView.find("tr:last"));
                $(this).parent().parent().prev().find("td").eq(0).html((parseInt(preindex)+1))
                return false;
            });
        });
    </script>
      <asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
                    <Columns>
                        <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
                        <asp:TemplateField HeaderText="Header 1">
                            <ItemTemplate>
                                <asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
                                    <asp:ListItem Value="-1">Select</asp:ListItem>
                                </asp:DropDownList>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Header 2">
                            <ItemTemplate>
                                <asp:DropDownList ID="DropDownList2" runat="server" AppendDataBoundItems="true">
                                    <asp:ListItem Value="-1">Select</asp:ListItem>
                                </asp:DropDownList>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Header 3">
                            <ItemTemplate>
                                <asp:DropDownList ID="DropDownList3" runat="server" AppendDataBoundItems="true">
                                    <asp:ListItem Value="-1">Select</asp:ListItem>
                                </asp:DropDownList>
                            </ItemTemplate>
                            <FooterStyle HorizontalAlign="Right" />
                            <FooterTemplate>
                                <asp:Button ID="btnAdd" runat="server" Text="Add" />
                            </FooterTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>

    CodeBehind:</div> <div>

     private ArrayList GetDummyData()
            {
                ArrayList arr = new ArrayList();
                arr.Add(new ListItem("Item1", "1"));
                arr.Add(new ListItem("Item2", "2"));
                arr.Add(new ListItem("Item3", "3"));
                arr.Add(new ListItem("Item4", "4"));
                arr.Add(new ListItem("Item5", "5"));
                return arr;
            }
    
            private void FillDropDownList(DropDownList ddl)
           {
                ArrayList arr = GetDummyData();
                foreach (ListItem item in arr)
                {
                    ddl.Items.Add(item);
                }
            }
    
            private void SetInitialRow()
            {
                DataTable dt = new DataTable();
                DataRow dr = null;
                //Define the Columns
                dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
                dt.Columns.Add(new DataColumn("Column1", typeof(string)));
                dt.Columns.Add(new DataColumn("Column2", typeof(string)));
                dt.Columns.Add(new DataColumn("Column3", typeof(string)));
                //Add a Dummy Data on Initial Load
                dr = dt.NewRow();
                dr["RowNumber"] = 1;
                dt.Rows.Add(dr);
                //Store the DataTable in ViewState
               ViewState["CurrentTable"] = dt;
                //Bind the DataTable to the Grid
                Gridview1.DataSource = dt;
                Gridview1.DataBind();
                //Extract and Fill the DropDownList with Data
                DropDownList ddl1 = (DropDownList)Gridview1.Rows[0].Cells[1].FindControl("DropDownList1");
                DropDownList ddl2 = (DropDownList)Gridview1.Rows[0].Cells[2].FindControl("DropDownList2");
                DropDownList ddl3 = (DropDownList)Gridview1.Rows[0].Cells[3].FindControl("DropDownList3");
                FillDropDownList(ddl1);
                FillDropDownList(ddl2);
                FillDropDownList(ddl3);
    
            }
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!Page.IsPostBack)
    
                {
                    SetInitialRow();
                }
            }

    Output:

    Best regards

    Cathy

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 9, 2018 9:21 AM

All replies

  • User632428103 posted

    Hello ashraf007,

    here is it my little sample 

     <script src="../../../Scripts/jquery-2.0.3.js"></script>
        <script type="text/javascript">
    
            var beginRow = '<tr>';
            var endRow = '</td></tr>';
    
            $(document).ready(function () {
    
                $('#btAdd').click(function () 
                {
                    var rowCount;
                    rowCount = $('#gv tr').length;
    
                    // add value textbox in last row of grid view
                    if ($('#gv tr').length > 1)
                    {
                        $('#gv tr:last').after(beginRow +
                            '<td>' + $('#tbName').val() + '</td>' +
                            '<td>' + $('#tbPrice').val() + '</td>' +
                            '<td>' + $('#tbCategory').val() + endRow);
    
                            //clear all field
                            $('#divContainer').find('input:text').each(function () { $('input:text[id=' + $(this).attr('id') + ']').val(''); }
                        );
                    }
                    else alert('Invalid!');
                });
            });
    
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
         <asp:GridView ID="gv" runat="server"  AutoGenerateColumns="False"  CssClass="grid">
                <Columns>
                    <asp:BoundField DataField="name" HeaderText="name" SortExpression="EmpName" />
                    <asp:BoundField DataField="price" HeaderText="price" SortExpression="Designation" />
                    <asp:BoundField DataField="category" HeaderText="category" SortExpression="Department" />
                </Columns>
            </asp:GridView>
        </div>
        <div id="divDisplayData">
                <ul>
                    <li><label>Employee Name: </label></li>
                    <li><input type="text" id="tbName" /></li>
                </ul>
                <ul>
                    <li><label>Price: </label></li>
                    <li><input type="text" id="tbPrice" /></li>
                </ul>
                <ul>
                    <li><label>Category: </label></li>
                    <li><input type="text" id="tbCategory" /></li>
                </ul>
                <ul>
                    <li></li>
                    <li>
                        <input type="button" id="btAdd" value="Add to Grid" />
                    </li>
                </ul>
            </div>
        </form>
    </body>
    </html>

    and on server side 

    protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    bindGrid();
                }
            }
    
            private void bindGrid()
            {
                //
                DataSet ds = new DataSet();
                string connection = ConfigurationManager.ConnectionStrings["DBTEST"].ConnectionString;
                using (SqlConnection conn = new SqlConnection(connection))
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = conn;
    
                    //
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.CommandText = "SELECT name, price, category From Product";
    
                    
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    adapter.Fill(ds);
                }
    
                //
                gv.DataSource = ds;
                gv.DataBind();
            }

    Monday, January 8, 2018 10:46 AM
  • User-707554951 posted

    Hi Ashraf007

    Working code as below:

     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
    <script type = "text/javascript">
        $(function () {
            var gridView = $("[id*=Gridview1]");
            var row = gridView.find("tr").eq(1).clone();
            $("[id*=btnAdd]").click(function () {
                //Reference the first row.
                var preindex = $(this).parent().parent().prev().find("td").eq(0).html();
    
                $("<tr>" + row.html() + "</tr>").insertBefore(gridView.find("tr:last"));
                $(this).parent().parent().prev().find("td").eq(0).html((parseInt(preindex)+1))
                return false;
            });
        });
    </script>
      <asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
                    <Columns>
                        <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
                        <asp:TemplateField HeaderText="Header 1">
                            <ItemTemplate>
                                <asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
                                    <asp:ListItem Value="-1">Select</asp:ListItem>
                                </asp:DropDownList>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Header 2">
                            <ItemTemplate>
                                <asp:DropDownList ID="DropDownList2" runat="server" AppendDataBoundItems="true">
                                    <asp:ListItem Value="-1">Select</asp:ListItem>
                                </asp:DropDownList>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Header 3">
                            <ItemTemplate>
                                <asp:DropDownList ID="DropDownList3" runat="server" AppendDataBoundItems="true">
                                    <asp:ListItem Value="-1">Select</asp:ListItem>
                                </asp:DropDownList>
                            </ItemTemplate>
                            <FooterStyle HorizontalAlign="Right" />
                            <FooterTemplate>
                                <asp:Button ID="btnAdd" runat="server" Text="Add" />
                            </FooterTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>

    CodeBehind:</div> <div>

     private ArrayList GetDummyData()
            {
                ArrayList arr = new ArrayList();
                arr.Add(new ListItem("Item1", "1"));
                arr.Add(new ListItem("Item2", "2"));
                arr.Add(new ListItem("Item3", "3"));
                arr.Add(new ListItem("Item4", "4"));
                arr.Add(new ListItem("Item5", "5"));
                return arr;
            }
    
            private void FillDropDownList(DropDownList ddl)
           {
                ArrayList arr = GetDummyData();
                foreach (ListItem item in arr)
                {
                    ddl.Items.Add(item);
                }
            }
    
            private void SetInitialRow()
            {
                DataTable dt = new DataTable();
                DataRow dr = null;
                //Define the Columns
                dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
                dt.Columns.Add(new DataColumn("Column1", typeof(string)));
                dt.Columns.Add(new DataColumn("Column2", typeof(string)));
                dt.Columns.Add(new DataColumn("Column3", typeof(string)));
                //Add a Dummy Data on Initial Load
                dr = dt.NewRow();
                dr["RowNumber"] = 1;
                dt.Rows.Add(dr);
                //Store the DataTable in ViewState
               ViewState["CurrentTable"] = dt;
                //Bind the DataTable to the Grid
                Gridview1.DataSource = dt;
                Gridview1.DataBind();
                //Extract and Fill the DropDownList with Data
                DropDownList ddl1 = (DropDownList)Gridview1.Rows[0].Cells[1].FindControl("DropDownList1");
                DropDownList ddl2 = (DropDownList)Gridview1.Rows[0].Cells[2].FindControl("DropDownList2");
                DropDownList ddl3 = (DropDownList)Gridview1.Rows[0].Cells[3].FindControl("DropDownList3");
                FillDropDownList(ddl1);
                FillDropDownList(ddl2);
                FillDropDownList(ddl3);
    
            }
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!Page.IsPostBack)
    
                {
                    SetInitialRow();
                }
            }

    Output:

    Best regards

    Cathy

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 9, 2018 9:21 AM