2012-05-23 12 views
3

上述錯誤發生在列表框上的SelectedIndexChanged click事件上。ListBox返回SelectedIndexChanged事件中的空字符串

在調試中返回的值是「」,但是當您查看網頁源代碼時,確實存在值。

這裏是我的列表框:

<asp:ListBox ID="lstBxMyList" runat="server" CssClass="binorderlst1" 
    DataTextField="myName" 
    DataValueField="myID" 
    OnSelectedIndexChanged ="lstBxMyList_SelectedIndexChanged" 
    AutoPostBack="true" Rows="10"> 
</asp:ListBox> 

這裏的事件:

protected void lstBxMyList_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    myID = Convert.ToInt32(lstBxSiteList.SelectedValue.ToString()); 

    ... rest of code 
} 

爲了完整這裏的數據綁定:

private void BindLstBxMyList(int myOtherID) 
    { 
     DataTable dt = new DataTable(); 
     SqlConnection conn; 
     SqlCommand comm; 

     using (conn = new SqlConnection(aSHconns.aconn)) 
     { 
      comm = new SqlCommand("myStoredProc", conn); 
      comm.CommandType = CommandType.StoredProcedure; 
      comm.Parameters.Add(new SqlParameter("@myOtherID", SqlDbType.Int)); 
      comm.Parameters["@myOtherID"].Value = myOtherID; 
      SqlDataAdapter sqlDa = new SqlDataAdapter(comm); 

      try 
      { 
       conn.Open(); 
       sqlDa.Fill(dt); 
       if (dt.Rows.Count > 0) 
       { 
        lstBxMyList.DataSource = dt; 
        lstBxMyList.DataTextField = "myName"; 
        lstBxMyList.DataValueField = "myID"; 
        lstBxMyList.DataBind(); 
       } 

      } 

      finally 
      { 
       conn.Close(); 
      } 
     } 

    } 

如果我恢復到一個SqlDataSource列表框的回報值。 Bt我需要重新填充列表,所以我需要數據綁定背後的代碼(除非有更好的方法)

那麼,爲什麼listbox的選擇值返回一個空字符串呢?任何幫助將受到感謝。

+0

你可以顯示你從哪裏調用BindLstBxMyList的代碼? –

+0

您是否在每次回發時調用BindLstBxMyList或檢查Page.IsPostBack。 –

+0

我在每次回發的Page_Load事件中調用它,因爲我希望它每次都刷新。 – ComfortablyNumb

回答

5

你有財產AutoPostBack =「True」這將使每個選定的索引更改回發。因此,在選擇索引更改事件之前,必須在綁定列表框的地方點擊頁面加載。所以,當它加載頁面時,選定的索引將被更改爲默認項目。所以,請嘗試下面的代碼。

protected void Page_Load(object sender, EventArgs e) 
     { 
      if (!IsPostBack) 
      { 
      //Bind your listbox here 
      } 
     } 
+0

if(!IsPostBack){//綁定你的列表框在這裏} –