locked
Move selected items from one listbox to another in C# RRS feed

  • Question

  • User-2004582644 posted

    Hi guys,

    This code re-initialize ListBox1 when append new item after Savepnusers complete successfully.

    Writing value in TextBox this value is appended on the ListBox1

    But I can't get all values or single value from ListBox1 to ListBox2, because the append new item disappears from ListBox1

    Please see this:

    My complete code below.

    Any suggestions?

    .cs page

    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

    <%@ 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>
    

    Wednesday, April 15, 2020 8:32 PM

Answers

  • User1535942433 posted

    Hi Chevy Marl Sunderland,

    Accroding to your description and codes,as far as I think,the problem is when you click the button,the page will be refresh and the listbox coudn't get the current data.I suggest you could use button click to insert data to database intead of ajax.

    More details,you could refer to below codes:

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

    Code-behind:

    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; }
            }
    
            //[WebMethod(EnableSession = true)]
            //[ScriptMethod]
            //public static void Savepnusers(pnnusers nnewuser)
            //{
            //    string sql = "INSERT INTO stored(Name) values('" + nnewuser.txuser.ToString() + "')";
            //    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", nnewuser.txuser.ToString());
            //        cmd.ExecuteNonQuery();
    
            //    }
            //    catch (Exception ex)
            //    {
            //        throw ex;
            //    }
            //    finally
            //    {
            //        conn.Close();
            //    }
            //}
    
            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();
            }

    Result:

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 16, 2020 9:27 AM

All replies

  • User1535942433 posted

    Hi Chevy Marl Sunderland,

    Accroding to your description and codes,as far as I think,the problem is when you click the button,the page will be refresh and the listbox coudn't get the current data.I suggest you could use button click to insert data to database intead of ajax.

    More details,you could refer to below codes:

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

    Code-behind:

    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; }
            }
    
            //[WebMethod(EnableSession = true)]
            //[ScriptMethod]
            //public static void Savepnusers(pnnusers nnewuser)
            //{
            //    string sql = "INSERT INTO stored(Name) values('" + nnewuser.txuser.ToString() + "')";
            //    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", nnewuser.txuser.ToString());
            //        cmd.ExecuteNonQuery();
    
            //    }
            //    catch (Exception ex)
            //    {
            //        throw ex;
            //    }
            //    finally
            //    {
            //        conn.Close();
            //    }
            //}
    
            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();
            }

    Result:

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 16, 2020 9:27 AM
  • User-2004582644 posted

    Hello Yijing Sun.

    Thank you for help.

    I have tried your code and perfectly working.

    Thursday, April 16, 2020 10:52 AM