Usher
Usher

Reputation: 2146

Dynamic grid on ASP.NET

I here to seek an advice ,what is the best approach.

here is the scenario.

I am building my project ASP.NET (C#)

I need to add an dynamic drop down box based on that two other text box related to drop down.

for example :

I have a button called "ADD LANDSCAPE", every time this triggered, i have to create an dynamic drop down "ddlLandscap" and two text boxes so the user can enter landscape value for each text box.

Can you guys please advise what's the best approach

Upvotes: 0

Views: 593

Answers (1)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CS1.aspx.cs" Inherits="workout.CS1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <link href="../jquery/jquery-ui.css" rel="stylesheet" />
    <script src="../jquery/jquery-1.12.0.js"></script>
    <script src="../jquery/jquery-ui.js"></script>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }

        .table {
            border: 1px solid #ccc;
            border-collapse: collapse;
        }

            .table th {
                background-color: #F7F7F7;
                color: #333;
                font-weight: bold;
            }

            .table th, .table td {
                padding: 5px;
                border: 1px solid #ccc;
            }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView ID="gvCustomers1" CssClass="table" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField HeaderText="Slno" ItemStyle-Width="50px" ItemStyle-CssClass="Slno">
                    <ItemTemplate>
                        <%# Eval("Slno") %>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name" ItemStyle-Width="150px" ItemStyle-CssClass="Name">
                    <ItemTemplate>
                        <%# Eval("Name") %>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Country" ItemStyle-Width="150px" ItemStyle-CssClass="Country">
                    <ItemTemplate>
                        <%# Eval("Country")%>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Option">
                    <ItemTemplate>
                        <asp:Button ID="lnkDelete" runat="server" Text="Delete" OnClientClick="Confirmationbox(this);" />
                        <asp:Button ID="btn_update" runat="server" Text="Update" OnClientClick="updateable(this);" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <br />
        <asp:Button ID="btnNewUser" runat="server" Text="Add" OnClientClick="return false;" />
        <asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Submit" OnClientClick="formatData()" />
        <br />

        <div id="dialog-form" title="Create new user">
            <p class="validateTips">All form fields are required.</p>
            <table border="0" cellpadding="0" cellspacing="0">
                <tr>
                    <td style="width: 150px">Name:<br />
                        <asp:TextBox ID="txtName" runat="server" Width="140" Text="" />
                    </td>
                    <td style="width: 150px">Country:<br />
                        <asp:TextBox ID="txtCountry" runat="server" Width="140" Text="" />
                    </td>
                </tr>
            </table>
        </div>

        <div id="dialog-form-edit" title="Edit user">
            <p class="validateTips">All form fields are required.</p>
            <asp:HiddenField ID="hdslno" runat="server" Value="" />
            <table border="0" cellpadding="0" cellspacing="0">
                <tr>
                    <td style="width: 150px">Name:<br />
                        <asp:TextBox ID="TextBox1" runat="server" Width="140" Text="" />
                    </td>
                    <td style="width: 150px">Country:<br />
                        <asp:TextBox ID="TextBox2" runat="server" Width="140" Text="" />
                    </td>
                </tr>
            </table>
        </div>

        <br />

        <script type="text/javascript">
            var dialog,editDialog;

            function formatData() {
                var formatdata = "";
                $( '#gvCustomers1 tr:gt(0)' ).each( function () {

                    $( this ).find( 'td' ).each( function () {
                        if ( $( this ).hasClass( "Slno" ) || $( this ).hasClass( "Name" ) || $( this ).hasClass( "Country" ) ) {
                            formatdata += $( this ).html() + "|";
                        }
                    } );
                    formatdata += ",";
                } );
                alert( formatdata );

                return false;
            }

            $(function () {
                dialog = $("#dialog-form").dialog({
                    autoOpen: false,
                    height: 300,
                    width: 350,
                    modal: true,
                    buttons: {
                        "Create an account": AddRow,
                        Cancel: function () {
                            dialog.dialog("close");
                        }
                    },
                    close: function () {
                        $("#txtName").val("");
                    },
                    open: function () {
                        var nr = $('#dialog-form').data('param');
                        if (nr) {
                            $("#txtName").val(nr);
                        } else {
                            $("#txtName").val("");
                        }
                    }
                });

                editDialog = $("#dialog-form-edit").dialog({
                    autoOpen: false,
                    height: 300,
                    width: 350,
                    modal: true,
                    buttons: {
                        "Create an account": UpdateRow,
                        Cancel: function () {
                            editDialog.dialog("close");
                        }
                    },
                    close: function () {
                        $("#txtName").val("");
                    },
                    open: function () {
                        var nr = $('#dialog-form-edit').data('param');
                        console.log(nr);
                        $( "#hdslno" ).val( nr.slno );
                        $("#TextBox1").val(nr.name);
                        $("#TextBox2").val(nr.country);
                    }
                });
            });

            $("#btnNewUser").button().on("click", function () {
                dialog.dialog("open");
            });

            function Confirmationbox(obj) {
                if (confirm("Do you want to delete this Customer?")) {
                    var row = $(obj).closest("tr");
                    row.remove();

                }
                return true;
            }

            function updateable(obj) {
                var row = $(obj).closest("tr");
                var slno = $(row).find("td").eq(0).html();
                var name = $(row).find("td").eq(1).html();
                var country = $(row).find("td").eq(2).html();

                try {
                    var json = {
                        slno: slno,
                        name: name,
                        country: country
                    };

                    editDialog.data('param', json).dialog("open");
                    event.preventDefault();
                } catch (e) {
                    alert(e);
                }

                return false;
            }

            function UpdateRow() {
                var slno = $( "#hdslno" ).val();
                var m_Name = $( "#TextBox1" ).val();
                var m_Country = $( "#TextBox2" ).val();
                var row = null;
                $( '#gvCustomers1 tr:gt(0)' ).each( function () {
                    $( this ).find( 'td' ).each( function () {
                        if ( $( this ).hasClass( "Slno" ) && $( this ).html() == slno ) {
                            row = $( this ).closest( "tr" );
                        }
                    } )
                } );
                if ( row ) {
                    $( row ).find( "td" ).eq( 1 ).html( m_Name );
                    $( row ).find( "td" ).eq( 2 ).html( m_Country );
                }
                editDialog.dialog( "close" );
                return false;
            }
            function AddRow() {
                //Reference the GridView.
                var gridView = document.getElementById("<%=gvCustomers1.ClientID %>");

                //Reference the TBODY tag.
                var tbody = gridView.getElementsByTagName("tbody")[0];

                //Reference the first row.
                var row = tbody.getElementsByTagName("tr")[1];

                //Check if row is dummy, if yes then remove.
                if (row.getElementsByTagName("td")[0].innerHTML.replace(/\s/g, '') == "") {
                    tbody.removeChild(row);
                }

                //Clone the reference first row.
                row = row.cloneNode(true);

                var legnth = gridView.rows.length;
                SetValue1(row, 0, "Slno", legnth);
                //Add the Name value to first cell.
                var txtName = document.getElementById("<%=txtName.ClientID %>");
                SetValue(row, 1, "name", txtName);

                //Add the Country value to second cell.
                var txtCountry = document.getElementById("<%=txtCountry.ClientID %>");
                SetValue(row, 2, "country", txtCountry);

                //Add the row to the GridView.
                tbody.appendChild(row);
                dialog.dialog("close");
                return false;
            }

            function SetValue(row, index, name, textbox) {
                row.cells[index].innerHTML = textbox.value;
                textbox.value = "";
            }
            function SetValue1(row, index, name,leng) {
                row.cells[index].innerHTML = leng;
            }
        </script>
        <asp:HiddenField ID="hdTableValues" runat="server" Value="" />
    </form>
</body>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace workout
{
    public partial class CS1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!this.IsPostBack)
            {
                this.BindGrid();
            }

        }

        private void BindGrid()
        {
            DataTable dt = new DataTable();
            string query = "SELECT '' Slno, Name, Country FROM dd_Detils";
            string constr = "Data Source=localhost;Initial Catalog=DataBase;User ID=sa;Password=globalfocus";
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = con;
                    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                    {
                        sda.SelectCommand = cmd;
                        sda.Fill(dt);
                    }
                }
            }

            if (dt.Rows.Count == 0)
            {
                //If no records then add a dummy row.
                dt.Rows.Add();
            }
            gvCustomers1.DataSource = dt;
            gvCustomers1.DataBind();
        }

        protected void Submit(object sender, EventArgs e)
        {
            int cnt = gvCustomers1.Rows.Count;

            if (!string.IsNullOrEmpty(Request.Form["name"]) && !string.IsNullOrEmpty(Request.Form["country"]))
            {
                //Fetch the Hidden Field values from the Request.Form collection.
                string[] names = Request.Form["name"].Split(',');
                string[] countries = Request.Form["country"].Split(',');

                //Loop through the values and insert into database table.
                for (int i = 0; i < names.Length; i++)
                {
                    string constr = "Data Source=localhost;Initial Catalog=Database;User ID=sa;Password=globalfocus";
                    using (SqlConnection con = new SqlConnection(constr))
                    {
                        using (SqlCommand cmd = new SqlCommand("INSERT INTO dd_Detils VALUES(@Name, @Country)"))
                        {
                            cmd.Parameters.AddWithValue("@Name", names[i]);
                            cmd.Parameters.AddWithValue("@Country", countries[i]);
                            cmd.Connection = con;
                            con.Open();
                            cmd.ExecuteNonQuery();
                            con.Close();
                        }
                    }
                }

                //Refresh the page to load GridView with records from database table.
                Response.Redirect(Request.Url.AbsoluteUri);
            }
        }
    }
}

Upvotes: 1

Related Questions