【问题标题】:Listbox Returns Empty String on SelectedIndexChanged Event列表框在 SelectedIndexChanged 事件上返回空字符串
【发布时间】:2012-05-23 15:29:53
【问题描述】:

上述错误发生在列表框上的 SelectedIndexChanged 点击事件上。

debug返回值是"",但是看网页源码肯定有值。

这是我的列表框:

<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 我需要重新填充列表,所以我需要数据绑定背后的代码(当然,除非有更好的方法)

那么为什么列表框选择的值返回一个空字符串?任何帮助将不胜感激。

【问题讨论】:

  • 你能显示你从哪里调用 BindLstBxMyList 的代码吗?
  • 您是在每次回发时调用 BindLstBxMyList 还是检查 Page.IsPostBack。
  • 我在每次回发的 Page_Load 事件中调用它,因为我希望它每次都刷新。

标签: c# asp.net listbox selectedindexchanged


【解决方案1】:

您有属性 AutoPostBack = "True" 这将在每个更改的选定索引上进行回发。因此,在它进入 Selected index changed 事件之前,它必须在绑定列表框的地方点击页面加载。因此,当它点击页面加载时,选定的索引将更改为默认项。所以,试试下面的代码。

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

【讨论】:

  • if(!IsPostBack) { //在这里绑定你的列表框 }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 2011-07-20
相关资源
最近更新 更多