I tried several times to check why I get this error even though my code is correct and there is no error. I want to retrieve the Name of the user but I get this error:
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. Line 28: com.Parameters.AddWithValue("@username", Session["username"].ToString());
C# code
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();
}
Tables
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])
);
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)
);
from Recent Questions - Stack Overflow https://ift.tt/3rzFFG3
https://ift.tt/eA8V8J
No comments:
Post a Comment