将所选项目从一个列表框移动到C#中的另一个列表

问题描述 投票:1回答:1

在Savepnusers成功完成后追加新项目时,此代码将重新初始化ListBox1。

在TextBox中写入值,该值附加在ListBox1上。

enter image description here

但是我无法从ListBox1到ListBox2获得所有值或单个值,因为附加的新项将从ListBox1中消失。

请参阅此:

enter image description here

下面我的完整代码。

有什么建议吗?

。cs页面

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.Odbc;
using System.Threading;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default : System.Web.UI.Page
{
    string sql;

    ArrayList arraylist1 = new ArrayList();
    ArrayList arraylist2 = new ArrayList();

    protected void btn4_Click(object sender, EventArgs e)
    {
        while (ListBox2.Items.Count != 0)
        {
            for (int i = 0; i < ListBox2.Items.Count; i++)
            {
                ListBox1.Items.Add(ListBox2.Items[i]);
                ListBox2.Items.Remove(ListBox2.Items[i]);
            }
        }
    }

    protected void btn3_Click(object sender, EventArgs e)
    {
        arraylist2 = new ArrayList();

        if (ListBox2.SelectedIndex >= 0)
        {
            for (int i = 0; i < ListBox2.Items.Count; i++)
            {
                if (ListBox2.Items[i].Selected)
                {
                    if (!arraylist2.Contains(ListBox2.Items[i]))
                    {
                        arraylist2.Add(ListBox2.Items[i]);
                    }
                }
            }
            for (int i = 0; i < arraylist2.Count; i++)
            {
                if (!ListBox1.Items.Contains(((ListItem)arraylist2[i])))
                {
                    ListBox1.Items.Add(((ListItem)arraylist2[i]));
                }
                ListBox2.Items.Remove(((ListItem)arraylist2[i]));
            }
            ListBox1.SelectedIndex = -1;
        }
    }

    protected void btn2_Click(object sender, EventArgs e)
    {
        while (ListBox1.Items.Count != 0)
        {
            for (int i = 0; i < ListBox1.Items.Count; i++)
            {
                ListBox2.Items.Add(ListBox1.Items[i]);
                ListBox1.Items.Remove(ListBox1.Items[i]);
            }
        }
    }

    protected void btn1_Click(object sender, EventArgs e)
    {
        arraylist1 = new ArrayList();

        if (ListBox1.SelectedIndex >= 0)
        {
            for (int i = 0; i < ListBox1.Items.Count; i++)
            {
                if (ListBox1.Items[i].Selected)
                {
                    if (!arraylist1.Contains(ListBox1.Items[i]))
                    {
                        arraylist1.Add(ListBox1.Items[i]);
                    }
                }
            }

            for (int i = 0; i < arraylist1.Count; i++)
            {
                if (!ListBox2.Items.Contains(((ListItem)arraylist1[i])))
                {
                    ListBox2.Items.Add(((ListItem)arraylist1[i]));
                }
                ListBox1.Items.Remove(((ListItem)arraylist1[i]));
            }
            ListBox2.SelectedIndex = -1;
        }
    }

    private void MTListBox1()
    {
        DataTable dt = new DataTable();

        sql = @String.Format(" SELECT NAME FROM `country` GROUP BY `NAME` ORDER BY SURFACEAREA DESC LIMIT 10; ");

        using (OdbcConnection cn =
            new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
        {
            using (OdbcCommand command =
                new OdbcCommand(sql, cn))
            {
                try
                {
                    command.Connection.Open();
                    OdbcDataAdapter sqlDa = new OdbcDataAdapter(command);
                    sqlDa.Fill(dt);

                    if (dt.Rows.Count > 0)
                    {
                        ListBox1.DataTextField = "NAME";
                        ListBox1.DataValueField = "NAME";
                        ListBox1.DataSource = dt;
                        ListBox1.DataBind();
                    }
                }
                catch (OdbcException ex)
                {
                    string msg = "Fetch Error:";
                    msg += ex.Message;
                    throw new Exception(msg);
                }
                finally
                {
                    command.Connection.Close();
                }
            }
        }
    }

    public class pnnusers
    {
        public string txuser { get; set; }
    }

    [WebMethod(EnableSession = true)]
    [ScriptMethod]
    public static void Savepnusers(pnnusers nnewuser)
    {
        string sql = @String.Format("INSERT INTO `stored` SELECT Name, NULL FROM Country WHERE Name=?;");

        using (OdbcConnection cn =
          new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
        {
            using (OdbcCommand command =
                    new OdbcCommand(sql, cn))
            {
                try
                {
                    command.Connection.Open();
                    command.Parameters.AddWithValue("param1", nnewuser.txuser.ToString());
                    command.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    command.Connection.Close();
                }
            }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            MTListBox1();
        }
    }
}

。aspx页面

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default"
    EnableEventValidation="false" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
    <script type="text/javascript">

        $(function () {
            $("[id*=imgsave]").bind("click", function () {
                var qString = "?" + window.location.href.split("?")[1];
                var nnewuser = {};

                nnewuser.txuser = $("[id*=txuser]").val();
                var txtUser = $("[id*=txuser]").val();

                $.ajax({
                    type: "POST",
                    url: "Default.aspx/Savepnusers" + qString,
                    data: '{nnewuser: ' + JSON.stringify(nnewuser) + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",

                    success: function (response) {
                        if ($("[id*=txuser]").val()) {
                            alert("OK");
                            alert(JSON.stringify(nnewuser));
                            if (txtUser) {
                                $("[id*=ListBox1]").append("<option value='" + nnewuser.txuser + "'>" + nnewuser.txuser + "</option>");
                            }
                        }
                    },

                    failure: function (response) {
                        alert(response.d);
                    },

                    error: function (response) {
                        alert(response.d);
                    },

                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("error : " + thrownError + JSON.stringify(nnewuser));
                    }
                });
                return false;
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div style="align-content: center;">
            <br />
            <asp:TextBox ID="txuser" runat="server" BackColor="Yellow" CssClass="pure-u-23-24"></asp:TextBox>
            <br />
            <asp:ImageButton ID="imgsave" runat="server"
                ImageUrl="/ImgFolder/Img.gif"
                OnClientClick="if (!confirm('Are you sure?')) return false;" />
            <br />
            LISTBOX1
            <br />
            <div>
                <asp:ListBox ID="ListBox1" runat="server"
                    SelectionMode="Multiple"
                    Height="250" Width="400"></asp:ListBox>
                LISTBOX2
            <asp:ListBox ID="ListBox2" runat="server"
                SelectionMode="Multiple"
                Height="250" Width="400"></asp:ListBox>
            </div>
            <br />
            <div style="align-content: center;">
                <asp:Button ID="btn1" runat="server" Text=">" OnClick="btn1_Click" Width="100" />
                <br />
                <asp:Button ID="btn2" runat="server" Text=">>" OnClick="btn2_Click" Width="100" />
                <br />
                <asp:Button ID="btn3" runat="server" Text="<" OnClick="btn3_Click" Width="100" />
                <br />
                <asp:Button ID="btn4" runat="server" Text="<<" OnClick="btn4_Click" Width="100" />
            </div>
        </div>
    </form>
</body>
</html>

enter image description here

c# json ajax listbox
1个回答
0
投票

根据您的描述和代码,据我认为,问题是当您单击按钮时,页面将刷新,列表框无法获取当前数据。我建议您可以使用按钮单击将数据插入到ajax的数据库接口中。

更多详细信息,您可以参考以下代码:

<form id="form1" runat="server">    
        <div style="align-content: center;">
            <br />
            <asp:TextBox ID="txuser" runat="server" BackColor="Yellow" CssClass="pure-u-23-24"></asp:TextBox>
            <br />
            <asp:Button ID="imgsave" runat="server"
                OnClientClick="return confirm('Are you sure?');" OnClick="imgsave_Click" />
            <br />
            LISTBOX1
            <br />
            <div>
                <asp:ListBox ID="ListBox1" runat="server"
                    SelectionMode="Multiple"
                    Height="250" Width="400"></asp:ListBox>
                LISTBOX2
            <asp:ListBox ID="ListBox2" runat="server"
                SelectionMode="Multiple"
                Height="250" Width="400"></asp:ListBox>
            </div>
            <br />
            <div style="align-content: center;">
                <asp:Button ID="btn1" runat="server" Text=">" OnClick="btn1_Click" Width="100" />
                <br />
                <asp:Button ID="btn2" runat="server" Text=">>" OnClick="btn2_Click" Width="100" />
                <br />
                <asp:Button ID="btn3" runat="server" Text="<" OnClick="btn3_Click" Width="100" />
                <br />
                <asp:Button ID="btn4" runat="server" Text="<<" OnClick="btn4_Click" Width="100" />
            </div>
        </div>
    </form>

隐藏代码:

        string sql;    
        ArrayList arraylist1 = new ArrayList();
        ArrayList arraylist2 = new ArrayList();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                MTListBox1();                  
            }                 
        }

        protected void btn1_Click(object sender, EventArgs e)
        {
            arraylist1 = new ArrayList();

            if (ListBox1.SelectedIndex >= 0)
            {
                for (int i = 0; i < ListBox1.Items.Count; i++)
                {
                    if (ListBox1.Items[i].Selected)
                    {
                        if (!arraylist1.Contains(ListBox1.Items[i]))
                        {
                            arraylist1.Add(ListBox1.Items[i]);
                        }
                    }
                }

                for (int i = 0; i < arraylist1.Count; i++)
                {
                    if (!ListBox2.Items.Contains(((ListItem)arraylist1[i])))
                    {
                        ListBox2.Items.Add(((ListItem)arraylist1[i]));
                    }
                    ListBox1.Items.Remove(((ListItem)arraylist1[i]));
                }
                ListBox2.SelectedIndex = -1;
            }
        }

        protected void btn2_Click(object sender, EventArgs e)
        {
            while (ListBox1.Items.Count != 0)
            {
                for (int i = 0; i < ListBox1.Items.Count; i++)
                {
                    ListBox2.Items.Add(ListBox1.Items[i]);
                    ListBox1.Items.Remove(ListBox1.Items[i]);
                }
            }
        }

        protected void btn3_Click(object sender, EventArgs e)
        {
            arraylist2 = new ArrayList();

            if (ListBox2.SelectedIndex >= 0)
            {
                for (int i = 0; i < ListBox2.Items.Count; i++)
                {
                    if (ListBox2.Items[i].Selected)
                    {
                        if (!arraylist2.Contains(ListBox2.Items[i]))
                        {
                            arraylist2.Add(ListBox2.Items[i]);
                        }
                    }
                }
                for (int i = 0; i < arraylist2.Count; i++)
                {
                    if (!ListBox1.Items.Contains(((ListItem)arraylist2[i])))
                    {
                        ListBox1.Items.Add(((ListItem)arraylist2[i]));
                    }
                    ListBox2.Items.Remove(((ListItem)arraylist2[i]));
                }
                ListBox1.SelectedIndex = -1;
            }
        }

        protected void btn4_Click(object sender, EventArgs e)
        {
            while (ListBox2.Items.Count != 0)
            {
                for (int i = 0; i < ListBox2.Items.Count; i++)
                {
                    ListBox1.Items.Add(ListBox2.Items[i]);
                    ListBox2.Items.Remove(ListBox2.Items[i]);
                }
            }
        }
        protected void MTListBox1()
        {
            string str, strSql;
            str = System.Configuration.ConfigurationManager.ConnectionStrings["aspnet-TestApplicationWithDatabase-20190820030542"].ConnectionString;
            SqlConnection conn = new SqlConnection(str);
            strSql = "select Name from stored";
            SqlCommand cmd = new SqlCommand(strSql, conn);
            try
            {
                conn.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                if (dt.Rows.Count > 0)
                {
                    ListBox1.DataTextField = "NAME";
                    ListBox1.DataValueField = "NAME";
                    ListBox1.DataSource = dt;
                    ListBox1.DataBind();
                }
            }
            catch (Exception ex)
            {
                string msg = "Fetch Error:";
                msg += ex.Message;
                throw new Exception(msg);
            }
            finally
            {
                conn.Close();
            }

        }
        public class pnnusers
        {
            public string txuser { get; set; }
        }

        protected void imgsave_Click(object sender, EventArgs e)
        {
            string sql = "INSERT INTO stored(Name) values(@param1)";
            string str;
            str = System.Configuration.ConfigurationManager.ConnectionStrings["aspnet-TestApplicationWithDatabase-20190820030542"].ConnectionString;
            SqlConnection conn = new SqlConnection(str);
            SqlCommand cmd = new SqlCommand(sql, conn);
            try
            {
                conn.Open();
                cmd.Parameters.AddWithValue("param1", txuser.Text);
                cmd.ExecuteNonQuery();

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }

            MTListBox1();
        }

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.