Этот код повторно инициализирует ListBox1 при добавлении нового элемента после успешного завершения Savepnusers.
При записи значения в TextBox это значение добавляется в ListBox1.
Но я не могу получить все значения или одно значение от ListBox1 до ListBox2, потому что добавляемый новый элемент исчезает из ListBox1.
Пожалуйста, посмотрите это:
Мой полный код ниже.
Есть предложения?
.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 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>