gpt4 book ai didi

c# - 使用 session 变量时如何解决 ASP.Net "Input string was not in a correct format"错误

转载 作者:太空宇宙 更新时间:2023-11-04 16:07:23 25 4
gpt4 key购买 nike

我试图从用户登录时设置的 ASP.NET session 变量中获取用户 ID。到目前为止我已经尝试过:

<asp:SqlDataSource ID="useridsource" runat="server">

<SelectParameters>
<asp:SessionParameter Name="myuser" SessionField="user" Type="string" />
</SelectParameters>

</asp:SqlDataSource>

从 session 变量中获取用户 ID 的 C# 代码:

int userid = Convert.ToInt16("SELECT  [ID] * FROM [users] WHERE ([email] = @myuser)");

查询然后将用户 ID 插入到 Post 表中:

string query = "INSERT INTO userpost(categoryID, userID, adtitle, addescription, adphoto, uploadeddate) VALUES(@categorydata, @userid, @adtitle, @description, @image, @date)";

我知道在我的代码中设置 int userid 存在问题,但我一直无法弄清楚如何解决它。任何帮助将不胜感激!

最佳答案

首先连接到数据库,执行你的SQL命令,然后将返回的ID转换成一个整数。

int userid;
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();

cmd.CommandText = "SELECT [ID] FROM [users] WHERE ([email] = @myuser)";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;

sqlConnection1.Open();

using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
userid = Convert.ToInt16(reader.GetValue(reader.GetOrdinal("ID")));
}
}

sqlConnection1.Close();

关于c# - 使用 session 变量时如何解决 ASP.Net "Input string was not in a correct format"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37034432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com