前台代码
<asp:ListBox ID="LB" runat="server" AutoPostBack="true" Width="100" Height="100">
<asp:ListItem>0</asp:ListItem>
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
</asp:ListBox>
<asp:Button ID="btn1" runat="server" Text="最上" onclick="btn1_Click" />
<asp:Button ID="btn5" runat="server" Text="最尾" onclick="btn5_Click"/>
<asp:Button ID="btn2" runat="server" Text="上一个" onclick="btn2_Click"/>
<asp:Button ID="btn3" runat="server" Text="下一个" onclick="btn3_Click"/>
<asp:Button ID="btn4" runat="server" Text="Up" CommandName="up" onclick="btn4_Click"/>
<asp:Button ID="btn6" runat="server" Text="Down" CommandName="down" onclick="btn4_Click"/>
后台代码
protected void btn1_Click(object sender, EventArgs e)
{
LB.SelectedIndex = 0;
}
protected void btn2_Click(object sender, EventArgs e)
{
if (LB.SelectedIndex > 0)
{
LB.SelectedIndex = LB.SelectedIndex - 1;
}
}
protected void btn3_Click(object sender, EventArgs e)
{
if (LB.SelectedIndex < LB.Items.Count - 1)
{
LB.SelectedIndex = LB.SelectedIndex + 1;
}
}
protected void btn5_Click(object sender, EventArgs e)
{
LB.SelectedIndex = LB.Items.Count - 1;
}
protected void btn4_Click(object sender, EventArgs e)
{
if (((Button)sender).CommandName == "up" && LB.SelectedIndex > 0 || ((Button)sender).CommandName == "down" && LB.SelectedIndex < LB.Items.Count - 1)
{
int index;
if (((Button)sender).CommandName == "up")
{
index = -1;
}
else
{
index = 1;
}
ListItem lt = new ListItem(LB.SelectedItem.Text, LB.SelectedItem.Value);
LB.Items[LB.SelectedIndex].Text = LB.Items[LB.SelectedIndex + index].Text;
LB.Items[LB.SelectedIndex].Value = LB.Items[LB.SelectedIndex + index].Value;
LB.Items[LB.SelectedIndex + index].Text = lt.Text;
LB.Items[LB.SelectedIndex + index].Value = lt.Value;
LB.SelectedIndex = LB.SelectedIndex + index;
}
}
注释:
if (((Button)sender).CommandName == "up" && LB.SelectedIndex > 0 || ((Button)sender).CommandName == "down" && LB.SelectedIndex < LB.Items.Count - 1)
//命令的发送者是谁将其转换成button;对应的是那个具体的button;控件ListBox的选中条目
{
int index;
if (((Button)sender).CommandName == "up")
{
index = -1;
}
else
{
index = 1;
}
ListItem lt = new ListItem(LB.SelectedItem.Text, LB.SelectedItem.Value);
//用来保存选中行的Text和Value
LB.Items[LB.SelectedIndex].Text = LB.Items[LB.SelectedIndex + index].Text;
LB.Items[LB.SelectedIndex].Value = LB.Items[LB.SelectedIndex + index].Value;
//将新的选中条目的Text和Value值赋值给选中的条目
LB.Items[LB.SelectedIndex + index].Text = lt.Text;
LB.Items[LB.SelectedIndex + index].Value = lt.Value;
//将先前选中的条目的Text和Value赋值给后选中的条目
LB.SelectedIndex = LB.SelectedIndex + index;
//设置选中条目的变化
}