ListBox控制元件實現上移、下移、迴圈上移、迴圈下移操作
阿新 • • 發佈:2019-02-02
一、先在前臺頁面中拖入一個listbox控制元件和四個button控制元件,可以對它們的樣式進行一下修改。
<style type="text/css">
.left {
float:left;
width:120px;
}
.right {
float:right;
width:80px;
}
.all {
width:200px;
}
</style>
二,在後臺相對應的button按鈕的click方法中加入程式碼。
protected void Button1_Click(object sender, EventArgs e) { //ListBox1.Items.Remove(ListBox1.SelectedItem); //上移 if (ListBox1.SelectedIndex > 0) { int idx = ListBox1.SelectedIndex; ListBox1.Items.Insert(ListBox1.SelectedIndex - 1, ListBox1.SelectedItem.ToString()); ListBox1.Items.RemoveAt(ListBox1.SelectedIndex); ListBox1.SelectedIndex = idx - 1; } } protected void Button2_Click(object sender, EventArgs e) { //下移 if (ListBox1.SelectedIndex < ListBox1.Items.Count - 1) { ListBox1.Items.Insert(ListBox1.SelectedIndex, ListBox1.Items[ListBox1.SelectedIndex + 1].ToString()); ListBox1.Items.RemoveAt(ListBox1.SelectedIndex + 1); } } protected void Button3_Click(object sender, EventArgs e) { //迴圈上移 if (ListBox1.SelectedIndex == 0) { ListBox1.Items.Insert(ListBox1.Items.Count,ListBox1.SelectedItem.ToString()); ListBox1.Items.RemoveAt(ListBox1.SelectedIndex); } } protected void Button4_Click(object sender, EventArgs e) { //迴圈下移 if (ListBox1.SelectedIndex == ListBox1.Items.Count-1) { ListBox1.Items.Insert(0, ListBox1.SelectedItem.ToString()); ListBox1.Items.RemoveAt(ListBox1.SelectedIndex); } }