C# 尝试在更改下拉菜单中的选择时返回主键
我有一个下拉列表,如下所示,我正在将priomary键作为DataValueEld取回C# 尝试在更改下拉菜单中的选择时返回主键,c#,asp.net,drop-down-menu,C#,Asp.net,Drop Down Menu,我有一个下拉列表,如下所示,我正在将priomary键作为DataValueEld取回 <asp:DropDownList ID="userNameDropDown" runat="server" DataSourceID="SqlDataSource1" DataTextField="Name" DataValueField="PK_User" OnSelectedIndexChanged="DropDownList1_SelectedIn
<asp:DropDownList ID="userNameDropDown" runat="server" DataSourceID="SqlDataSource1"
DataTextField="Name" DataValueField="PK_User" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="true">
</asp:DropDownList>
</span>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT [PK_User], [Name] FROM [User] ORDER BY CASE WHEN [LoginName] = @userLoggedIn THEN 1 ELSE 2 END, [Name]">
<SelectParameters>
<asp:QueryStringParameter Name="userLoggedIn" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
我发现以下错误,不明白原因:
A first chance exception of type 'System.InvalidCastException' occurred in App_Web_uhtjotwm.dll
System.InvalidCastException: Specified cast is not valid.
at user_nonscrumstories.getRecentStoryPK() in c:\Documents and Settings\tunnelld\My Documents\Visual Studio 2010\WebSites\ZSRBlank18\user\nonscrumstories.aspx.cs
编辑:
问题出在
getRecentStoryPK
上,没有看到粘贴的代码与此错误相关异常抛出的确切行是什么?是返回null的result=
行,还是.AddWithValue
的用户名下拉列表。SelectedItem.Value
实际上不是int
。。。?
A first chance exception of type 'System.InvalidCastException' occurred in App_Web_uhtjotwm.dll
System.InvalidCastException: Specified cast is not valid.
at user_nonscrumstories.getRecentStoryPK() in c:\Documents and Settings\tunnelld\My Documents\Visual Studio 2010\WebSites\ZSRBlank18\user\nonscrumstories.aspx.cs
private string getRecentStoryPK()
{
//userNameDropDown.DataBind();
SqlConnection conn = new SqlConnection();
//create array to store results of select query
int result = 0;
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
try
{
//open SQL connection
conn.Open();
//create SQL command
SqlCommand getRecentStoryPK = new SqlCommand("SELECT MAX([PK_NonScrumStory]) FROM [NonScrumStory] WHERE [UserId] = @userIdParam", conn);
//create and assign parameters
getRecentStoryPK.Parameters.AddWithValue("@userIdParam", Int32.Parse(userNameDropDown.SelectedItem.Value));
result = (int)getRecentStoryPK.ExecuteScalar();
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.ToString());
result = -1;
}
finally
{
conn.Close();
}
//return populated string
return result.ToString();
}