日期:2014-05-20  浏览次数:20854 次

有关listbox的问题
我写了两个listbox

后台代码如下:
protected void Button3_Click(object sender, EventArgs e)
  { try {
  ListBox1.Items.Add(ListBox2.SelectedItem);
  ListBox2.Items.Remove(ListBox2 .SelectedItem);}
  catch (NullReferenceException e1)
  {Response .Write ("no selected!");}
  }
  protected void Button2_Click(object sender, EventArgs e)
  {try {
  ListBox2.Items.Add(ListBox1.SelectedItem);
  ListBox1.Items.Remove(ListBox1.SelectedItem);
  }
  catch (NullReferenceException e2)
  { Response.Write("no selected!"); }
  }


前台代码:
<asp:ListBox ID="ListBox1" runat="server" Style="z-index: 107; left: 131px; position: absolute;
  top: 321px" SelectionMode="Multiple" DataTextField="name" DataValueField="name" Height="138px" Width="322px" ></asp:ListBox>
  <asp:ListBox ID="ListBox2" runat="server" Style="z-index: 108; left: 193px; position: absolute;
  top: 185px" OnSelectedIndexChanged="ListBox2_SelectedIndexChanged" SelectionMode="Multiple">
  <asp:ListItem>hello!</asp:ListItem>
  <asp:ListItem>ok!</asp:ListItem>
  <asp:ListItem>good!</asp:ListItem>
  <asp:ListItem>fine!</asp:ListItem></asp:ListBox>
  <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Style="z-index: 109;
  left: 67px; position: absolute; top: 142px" Text="Button" />
  <asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Style="z-index: 111;
  left: 194px; position: absolute; top: 140px" Text="Button" />
  <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:exConnectionString3 %>"
  SelectCommand="SELECT [name] FROM [tb1]"></asp:SqlDataSource>


现在显示都是正常的,当我选中listbox中的某个选项的时候,能够将其移动到对面的listbox中去。
问题是,当我没有选择listbox中的任何选项时,单击button,会抛出一个异常。
我在后台进行了捕获,但仍然报出此错。
请问,这里的try,catch语句应该写到哪里为好。

------解决方案--------------------
string listBox1 = this.ListBox1.SelectedItem.Text;
this.ListBox2.Items.Add(listBox1);
this.ListBox1.Items.Remove(listBox1);

<asp:ListBox ID="lst_left" runat="server" SelectionMode="Multiple" Height="203px"
Width="130px"></asp:ListBox>
<asp:ListBox ID="lst_center" runat="server" SelectionMode="Multiple" Height="203px" Width="130px"></asp:ListBox>
<input type="button" id="btn_leftToCenter" value="右移" onclick="MoveOption(document.getElementById('lst_left'),document.getElementById('lst_center'))" />
<input type="button" id="btn_centerToLeft" value="左移" onclick="MoveOption(document.getElementById('lst_center'),document.getElementById('lst_left'))" />

function MoveOption(fromSel,toSel)
{
var fromOp=fromSel.options;
var toOp=toSel.options;
var selectedFlag=false;
for(var i=0;i<fromOp.length;i++)
{
if(fromOp[i].selected)
{
selectedFlag=true;
var selectedOp=document.createElement("option");
selectedOp.text=fromOp[i].text;
selectedOp.value=fromOp[i].value;

toSelLength=toOp.length;