簡體   English   中英

Session["username"] 檢索用戶名

[英]Session["username"] retrive username

即使我的代碼正確且沒有錯誤,我也嘗試了幾次檢查為什么會出現此錯誤。 我想檢索用戶的名稱,但出現此錯誤:

當前 web 請求執行期間發生未處理的異常。 請查看堆棧跟蹤以獲取有關錯誤及其源自代碼的位置的更多信息。 異常詳細信息:System.NullReferenceException:Object 引用未設置為 object 的實例。 第 28 行:com.Parameters.AddWithValue("@username", Session["username"].ToString());

Cs代碼

protected void GridView_Items_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            var index = int.Parse(e.CommandArgument.ToString());
            var selected_Row = GridView_Items.Rows[index];
            int Id = int.Parse(selected_Row.Cells[0].Text);
            SqlCommand com = new SqlCommand("INSERT INTO order(itemid,username,Buydate) VALUES(@itemid,@username,@Buydate)", conn);
            com.Parameters.AddWithValue("@itemid", Id);
            com.Parameters.AddWithValue("@username", Session["@username"].ToString());
            com.Parameters.AddWithValue("@Buydate", DateTime.Now);

            SqlCommand com2 = new SqlCommand("update Items set Quantity=Quantity-1 where Id=@Id", conn);

            com2.Parameters.AddWithValue("@Id", Id);
            decimal Price = decimal.Parse(selected_Row.Cells[2].Text);

            if (selected_Row.Cells[4].Text == "True")
            {
                var discount = Price * 0.10m;
                Price = Price - discount;
                Label_Items.Text = "You Have Bought " + selected_Row.Cells[1].Text + " For " + Price + " With Discount Of " + discount;
            }
            else

            { Label_Items.Text = "You Have Bought " + selected_Row.Cells[1].Text + " For " + Price; }

            conn.Open();
            com2.ExecuteNonQuery();
            conn.Close();
        }

Order table
CREATE TABLE [dbo].[order] (
    [itemid]   INT          NOT NULL,
    [username] VARCHAR (50) NOT NULL,
    [Buydate]  DATE         NOT NULL,
    CONSTRAINT [compkey] PRIMARY KEY CLUSTERED ([itemid] ASC, [username] ASC),
    CONSTRAINT [FK_order_ToTable] FOREIGN KEY ([itemid]) REFERENCES [dbo].[items] ([Id]),
    CONSTRAINT [FK_order_ToTable_1] FOREIGN KEY ([username]) REFERENCES [dbo].[usersall] ([name])
);
Items table 
CREATE TABLE [dbo].[items] (
    [Id]          INT          NOT NULL,
    [name]        VARCHAR (50) NULL,
    [price]       INT          NULL,
    [quantity]    INT          NULL,
    [discountYes] BIT          NULL,
    [discountNo]  BIT          NULL,
    [category]    VARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

你有一個錯誤,更換

 com.Parameters.AddWithValue("@username", Session["@username"].ToString());

 com.Parameters.AddWithValue("@username", Session["username"].ToString());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM