listbox移位

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {//两个按妞使用一个实践。COMMANNAME 一个为UP 一个为DOWN
        //声明一个变量INDEX
        //如果满足第一个条件那么INDEX为-1,因为你要实现的功能是像上移动,所以索引要减1
        //如果不满足那就为+1像上移动,因为只有两个按妞来响应一个时间。
        //
        if (((Button)sender).CommandName == "up" && ListBox1.SelectedIndex > 0 || ((Button)sender).CommandName == "down" && ListBox1.SelectedIndex < ListBox1.Items.Count - 1)
        {
            int index;
            if (((Button)sender).CommandName == "up")
            {
                index = -1;
            }
            else
            {
                index = 1;
            }
            //声明一个LISTITEM对象把选定的值和文本传进去
            ListItem lt = new ListItem(ListBox1.SelectedItem.Text, ListBox1.SelectedValue);
            //[ListBox1.SelectedIndex]为索引值然后讲ListBox1.Items[ListBox1.SelectedIndex].Text的值
            //传给ListBox1.Items[ListBox1.SelectedIndex + index].Text
            //ListBox1.SelectedIndex + index是经过转换后的索引
            ListBox1.Items[ListBox1.SelectedIndex].Text = ListBox1.Items[ListBox1.SelectedIndex + index].Text;
            ListBox1.Items[ListBox1.SelectedIndex].Value = ListBox1.Items[ListBox1.SelectedIndex + index].Text;
            ListBox1.Items[ListBox1.SelectedIndex + index].Text = lt.Text;
            ListBox1.Items[ListBox1.SelectedIndex + index].Value = lt.Value;
            ListBox1.SelectedIndex = ListBox1.SelectedIndex + index;

        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {

    }
    protected void Button3_Click(object sender, EventArgs e)
    {//光标的索引移动到0 也就是第一个位置
        ListBox1.SelectedIndex = 0;
    }
    protected void Button4_Click(object sender, EventArgs e)
    {
        ListBox1.SelectedIndex = ListBox1.SelectedIndex - 1;

    }
    protected void Button5_Click(object sender, EventArgs e)
    {
        ListBox1.SelectedIndex = ListBox1.SelectedIndex + 1;
    }
    protected void Button6_Click(object sender, EventArgs e)
    {
        ListBox1.SelectedIndex = ListBox1.Items.Count - 1;
    }
}

 

你可能感兴趣的:(listbox)