Sha*_*one 1 c# asp.net session drop-down-menu
我正在尝试将下拉列表的值传递给会话变量,然后将此值转换为审阅页面的文本标签.然后需要将此值传递给sql表(不是问题).问题在于每当我尝试调用标签中的下拉列表的值(或索引,我已尝试过两者)时,我都会得到一个null异常.这是我在第一页上的一个下拉列表的代码,以及尝试在下一个页面上创建的会话中绑定它:FirstPage.aspx
<asp:DropDownList ID="ddlInnoc" runat="server">
<asp:ListItem Value="0">No</asp:ListItem>
<asp:ListItem Value="1">Yes</asp:ListItem>
</asp:DropDownList>
Run Code Online (Sandbox Code Playgroud)
FirstPage.aspx.cs
Session["Jabs"] = ddlInnoc.SelectedIndex;
Run Code Online (Sandbox Code Playgroud)
SecondPage.aspx
<asp:Label ID="lblJabs" runat="server"></asp:Label>
Run Code Online (Sandbox Code Playgroud)
SecondPage.aspx.cs
lblJabs.Text = Session["Jabs"].ToString();
Run Code Online (Sandbox Code Playgroud)
请有人告诉我,我只是愚蠢!我收到的例外情况如下:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 11: {
Line 12: //Capture session values from previous page and send to relevant labels
Line 13: **lblGroup.Text = Session["NoInGroup"].ToString();**
Line 14: lblFirstName.Text = Session["FirstName"].ToString();
Line 15: lblMiddleName.Text = Session["MiddleName"].ToString();
Run Code Online (Sandbox Code Playgroud)
有点奇怪的是,我可以成功地在不同的页面上获取不同DropDownList的SelectedIndex.它让我撕开我的头发!
在打开第二页之前,请确保您正在进行回发.
Session["Jabs"] = ddlInnoc.SelectedIndex;应该在selectedindexchanged方法中,并且应该在下拉列表中设置autpostback,例如:
<asp:DropDownList ID="ddlInnoc" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlInnoc_SelectedIndexChanged">
<asp:ListItem Value="0">No</asp:ListItem>
<asp:ListItem Value="1">Yes</asp:ListItem>
</asp:DropDownList>
Run Code Online (Sandbox Code Playgroud)
这个方法看起来像这样:
protected void ddlProject_SelectedIndexChanged(object sender, EventArgs e)
{
//if you want "0" or "1"
Session["Jabs"] = ddlInnoc.SelectedIndex;
//if you want "Yes" or "No"
//Session["Jabs"] = ddlInnoc.SelectedItem.Text;
//also if you want "0" or "1"
//Session["Jabs"] = ddlInnoc.SelectedValue;
}
Run Code Online (Sandbox Code Playgroud)
在大多数情况下,您可能不希望选择索引,因为这只是下拉列表中项目的顺序
要确保会话始终填充,您可以在Page_Load上设置它:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Session["Jabs"] = ddlInnoc.SelectedIndex;
}
}
Run Code Online (Sandbox Code Playgroud)
另外:当使用Session时,你应该始终知道Sessions可能会过期,因此在使用之前你应该总是检查NULL:
SecondPage.aspx.cs
lblJabs.Text = (Session["Jabs"] == null ? "Default Value" : Session["Jabs"].ToString());
Run Code Online (Sandbox Code Playgroud)