我有一个下拉列表,如下所示,我将主键作为 DataValueEield 取回。
<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>
当我更改下拉菜单中的选择时,我试图从中检索主键:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine(userNameDropDown.SelectedItem.Value);
}
我收到以下错误,不明白为什么:
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();
}