Listbox在SelectedIndexChanged事件上返回空字符串

Com*_*umb 3 c# asp.net listbox selectedindexchanged

上一个错误发生在列表框上的SelectedIndexChanged单击事件上.

在调试中返回的值是"",但是当你查看网页源代码时肯定有值.

这是我的列表框:

<asp:ListBox ID="lstBxMyList" runat="server" CssClass="binorderlst1"
     DataTextField="myName" 
     DataValueField="myID" 
     OnSelectedIndexChanged ="lstBxMyList_SelectedIndexChanged"
     AutoPostBack="true" Rows="10">
</asp:ListBox>
Run Code Online (Sandbox Code Playgroud)

这是活动:

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

    ... rest of code
}
Run Code Online (Sandbox Code Playgroud)

为了完整性,这里是数据绑定:

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();
            }
        }

    }
Run Code Online (Sandbox Code Playgroud)

如果我恢复到SqlDataSource,列表框将返回值.Bt我需要重新填充列表,所以我需要databind背后的代码(除非有更好的方法)

那么为什么列表框选中的值会返回一个空字符串?我们将非常感激地提供任何帮助.

Pra*_*tta 6

你有属性AutoPostBack ="True"这将使每个选定的索引的回发发生变化.因此,在进入选定索引更改事件之前,它必须在您绑定列表框的位置点击页面加载.因此,当它达到页面加载时,所选索引将更改为默认项目.因此,请尝试以下代码.

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
             //Bind your listbox here
            }
         }
Run Code Online (Sandbox Code Playgroud)