列表框事件未在asp.net

时间:2015-09-24 06:04:11

标签: c# asp.net

我想在选择ListBox的SelectedIndexChanged事件时从数据库加载记录。我没有在我的表单中使用更新面板控件,所以很好。现在我想使用更新面板控件,这样每次从列表框中选择一个项目时我的表单都不会回发。我试过但不会按预期工作。请帮助我克服我面临的这个问题。

.aspx代码

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" >
        <ContentTemplate>
            <asp:ListBox ID="lstTest" runat="server" AutoPostBack="True" Width="450px" OnSelectedIndexChanged="lstTest_SelectedIndexChanged"></asp:ListBox>
           <asp:TextBox ID="txtReport" runat="server"></asp:TextBox>
           <asp:TextBox ID="txtImression" runat="server"></asp:TextBox>
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="lstTest" EventName="SelectedIndexChanged" />
        </Triggers>
    </asp:UpdatePanel>

背后的.cs代码

protected void lstTest_SelectedIndexChanged(object sender, EventArgs e)
{
    int _serviceid = Convert.ToInt32(lstTest.SelectedValue);

    txtReport.Text = string.Empty;
    txtImression.Text = string.Empty;

    SqlConnection con = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "[get_rad_results]";
    cmd.Parameters.Add("@ServiceId", SqlDbType.Int).Value = _serviceid;
    cmd.Connection = con;


    try
    {
        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();

        if (dr.Read())
        {
            txtReport.Text = dr["Report"].ToString();
            txtImression.Text = dr["Impression"].ToString();
        }
    }

    catch (Exception ex)
    {
        Response.Write("Error occured: " + ex.Message.ToString());
    }

    finally
    {
        con.Close();
        con.Dispose();
    }
}

1 个答案:

答案 0 :(得分:-1)

也许你确实错过了aspx代码中的 script manager ?我做了一个适合我的小例子。

ASPX代码

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:ListBox ID="ListBox1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"></asp:ListBox>
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="ListBox1" EventName="SelectedIndexChanged" />
    </Triggers>
</asp:UpdatePanel>

代码

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        // demo values
        for (int i = 0; i < 10; i++)
        {
            ListBox1.Items.Add("value " + i);
        }

    }
}

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    Debug.WriteLine(ListBox1.SelectedItem);
}

如果我错过了什么,请告诉我。