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

Posted

技术标签:

【中文标题】在 C# 中将所选项目从一个列表框移动到另一个列表框【英文标题】:Move selected items from one listbox to another in C# 【发布时间】:2020-07-29 08:23:51 【问题描述】:

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

在 TextBox 中写入值,此值将附加到 ListBox1。

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

请看这个:

下面是我的完整代码。

有什么建议吗?

.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>

【问题讨论】:

【参考方案1】:

根据您的描述和代码,据我所知,问题是当您单击按钮时,页面将刷新并且列表框无法获取当前数据。 我建议您可以使用按钮单击将数据插入数据库而不是 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();
        

结果:

【讨论】:

以上是关于在 C# 中将所选项目从一个列表框移动到另一个列表框的主要内容,如果未能解决你的问题,请参考以下文章

我想将选定的项目从一个列表移动到另一个

PySimpleGui:如何将值从一个列表框添加到另一个列表框

复制并删除所选的列表框项目

如何在 Android Java 中将 1000 多个项目列表从一个 Activity 发送到另一个?

从DblClick上的列表框导航到所选项目(excel)

删除所选项目列表框AS3