private void bandlist2()
{
//创建数据库连接字符串
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
//打开数据库
con.Open();
//定义查询orders表中订单的名称
string cmdtext="select shipname from orders";
//创建数据适配器
SqlDataAdapter sda=new SqlDataAdapter(cmdtext,con);
//创建数据集
DataSet ds=new DataSet();
//填充数据集
sda.Fill(ds,"orders");
//设定list2的数据源
ListBox2.DataSource=ds.Tables["orders"].DefaultView;
//设定list2控件的datavaluefield属性
ListBox2.DataValueField = "shipname";
//将数据绑定到list2
ListBox2.DataBind();
//关闭数据库连接
con.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//调用bandlist2()函数在list2控件中显示数据
bandlist2();
}
}
protected void ListBox2_SelectedIndexChanged(object sender, EventArgs e)
{
//获取list2控件中选择项的值,并显示在labout控件中
this.Label1.Text = "你选择了:<font color=red>" + ListBox2.SelectedItem.Text + "</font>";
}
protected void Button1_Click(object sender, EventArgs e)
{
//判断textbox文本框中的是否输入为空
if (TextBox1.Text == string.Empty)
{
Response.Write("请输入内容");
}
else
{
//获取用户在文本框中输入的值
string aa = TextBox1.Text;
//获取的数据添加到List控件中
this.ListBox1.Items.Add(aa);
this.TextBox1.Text = string.Empty;
//提示添加信息成功
this.Label1.Text = "您刚才添加了" + aa + "";
}
}
protected void move_Click(object sender, EventArgs e)
{
if (ListBox1.SelectedValue == string.Empty)
{
Response.Write("请选择要转移的值");
}
else
{
//获取list中选择的值
string bb = ListBox1.SelectedValue;
//移除listbox1中的值
ListBox1.Items.Remove(bb);
//将list1中选择的值添加到list2控件的集合中
ListBox2.Items.Add(bb);
}
}
protected void down_Click(object sender, EventArgs e)
{
//判断选择的是否是最后一项
if (ListBox1.SelectedIndex >= 0 && ListBox1.SelectedIndex < ListBox1.Items.Count - 1) ;
{
//获取所选择的文本
string name = ListBox1.SelectedItem.Text;
//获取选项的ID
string id = ListBox1.SelectedValue;
//获取选择项的索引值
int index = ListBox1.SelectedIndex;
ListBox1.SelectedItem.Text = ListBox1.Items[index + 1].Text;
ListBox1.SelectedItem.Value = ListBox1.Items[index + 1].Value;
ListBox1.Items[index + 1].Text = name;
ListBox1.Items[index + 1].Value = id;
//设定下一项为当前项
ListBox1.SelectedIndex++;
}
}
protected void up_Click(object sender, EventArgs e)
{
//获取选择的项是不是你第一项
if (ListBox1.SelectedIndex > 0)
{
//获取当前所选择的信息
string name = ListBox1.SelectedItem.Text;
string id = ListBox1.SelectedValue;
int index = ListBox1.SelectedIndex;
//交换上一项与选择项的信息
ListBox1.SelectedItem.Text = ListBox1.Items[index - 1].Text;
ListBox1.SelectedItem.Value = ListBox1.Items[index - 1].Value;
ListBox1.Items[index - 1].Text = name;
ListBox1.Items[index - 1].Value= id;
//设定上一项为当前选择项
ListBox1.SelectedIndex--;
}
}
protected void remove_Click(object sender, EventArgs e)
{
//判断是否选择数据
if (ListBox1.SelectedIndex > -1)
{
//应用for循环获取list1控件中的数据项
for (int m = ListBox1.Items.Count - 1; m >= 0; m--)
{
//判断获取的数据项是否被选择
if (this.ListBox1.Items[m].Selected == true)
{
//删除被选择的项
ListBox1.Items.Remove(ListBox1.Items[m]);
}
}
}
else
{
this.Label1.Text = "请在左边选择所要选择的数据项";
}
}