簡體   English   中英

ASP.NET上的動態網格

[英]Dynamic grid on ASP.NET

我在這里征求意見,什么是最好的方法。

這是場景。

我正在構建我的項目ASP.NET(C#)

我需要基於與下拉列表相關的其他兩個文本框添加一個動態下拉框。

例如 :

我有一個名為“ ADD LANDSCAPE”的按鈕,每次觸發時,我都必須創建一個動態下拉菜單“ ddlLandscap”和兩個文本框,以便用戶可以為每個文本框輸入景觀值。

你們能告訴我最好的方法是什么

<%@ 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);
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM