Hjälp med SQLserver och C# i .NET

Permalänk
Medlem

Hjälp med SQLserver och C# i .NET

Jag försöker fixa en add to cart knapp men jag får ett error msg som jag inte vet hur jag kommer runt. Det känns som det är USERID som ska ändras men jag vet inte till vad. några idéer?
min ~aspx.cs ser ut så här.

protected void btnAddtoCart_Click(object sender, EventArgs e) { Int64 PID = Convert.ToInt64(Request.QueryString["PID"]); using (SqlConnection con1 = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("select * from tblCart where PID='" + PID + "'", con1)) { cmd.CommandType = CommandType.Text; using (SqlDataAdapter sda = new SqlDataAdapter(cmd)) { DataTable dt = new DataTable(); sda.Fill(dt); if (dt.Rows.Count > 0) { Int32 updateQty = Convert.ToInt32(dt.Rows[0][8].ToString()); Int32 UserID = Convert.ToInt32(Session["USERID"].ToString()); using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RayOfbDB"].ConnectionString)) { SqlCommand cmdU = new SqlCommand("UPDATE tblCart SET Qty =@Quantity WHERE PID=@CartPID", con); cmdU.Parameters.AddWithValue("@Quantity", updateQty + 1); cmdU.Parameters.AddWithValue("@CartPID", PID); con.Open(); cmdU.ExecuteNonQuery(); con.Close(); } } else { Int32 UserID = Convert.ToInt32(Session["USERID"].ToString()); using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RayOfbDB"].ConnectionString)) { string sqlQuery = "insert into tblCart values (@UID,@PID,@PName,@PPrice,@PSelPrice,@Qty)"; SqlCommand myCmd = new SqlCommand(sqlQuery, con); myCmd.Parameters.AddWithValue("@UID", UserID); myCmd.Parameters.AddWithValue("@PID", Session["CartPID"].ToString()); myCmd.Parameters.AddWithValue("@PName", Session["myPName"].ToString()); myCmd.Parameters.AddWithValue("@PPrice", Session["myPPrice"].ToString()); myCmd.Parameters.AddWithValue("@PSelPrice", Session["myPSelPrice"].ToString()); myCmd.Parameters.AddWithValue("@Qty", "1"); con.Open(); Int64 CartID = Convert.ToInt64(myCmd.ExecuteScalar()); con.Close(); } } } } } }

felmeddelandet jag får är "Object reference not set to an instance of an object.
Description: 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."

och SQL bordet tblCart ser ut så här.

create table tblCart
(
CartID int primary key identity(1,1),
UID int,
PID int,
PName nvarchar(MAX),
PPrice money,
PSelPrice money,
SubPAmount as PPrice * Qty,
SubSAmount as PSelPrice * Qty,
Qty int,
)

Permalänk
Medlem

jag rekommenderar att du läser på rent allmänt om hur man bör göra, börja på t.ex.

https://docs.microsoft.com/en-us/dotnet/framework/data/adonet...

Hela din kod är en väntande sql-injection

mvh Lazze

Permalänk
Medlem
Skrivet av Tea42BBS:

jag rekommenderar att du läser på rent allmänt om hur man bör göra, börja på t.ex.

https://docs.microsoft.com/en-us/dotnet/framework/data/adonet...

Hela din kod är en väntande sql-injection

mvh Lazze

Ja jag var super trött igår kväll så jag hade fel namn. USERID ska vara "Username" i mitt fall. för det är vad den som är inloggada är kallad. verkligen försökt hitta en vettig addtoCart button kod över hela nätet men ingen finns till SQLserver.

Permalänk
Medlem
Skrivet av karu83:

Ja jag var super trött igår kväll så jag hade fel namn. USERID ska vara "Username" i mitt fall. för det är vad den som är inloggada är kallad. verkligen försökt hitta en vettig addtoCart button kod över hela nätet men ingen finns till SQLserver.

om du kör c# / net / ado.net så är det ingen specifik kod för just sql server - det är "generisk kod" för sql-databaser.

SQL injection risken kommer när man klipper ihop SQL command i kod direkt med user-input - oftast ett stor no-no

Så kolla in ado.net, linq for sql / linq

o nästa steg, Entity Framework - kanon för att jobba med klassiska sql databaser, fast med objekt - du slipper se databasen

Lycka till!

mvh Lazze

Permalänk
Skrivet av karu83:

Jag försöker fixa en add to cart knapp men jag får ett error msg som jag inte vet hur jag kommer runt. Det känns som det är USERID som ska ändras men jag vet inte till vad. några idéer?
min ~aspx.cs ser ut så här.
.............................

Några exempel med ADO.NET, Dapper och Entity Framework.

Jag har la till kommentarer som warning, för att peka på problemen med Cart som du gör i koden.

namespace AdoNetSample { using System; using System.Data; using Microsoft.Data.SqlClient; // using only nuget package Microsoft.Data.SqlClient internal class Program { private static void Main() { Console.WriteLine("ADO.NET shopping sample."); const string host = "(LocalDB)\\MSSQLLocalDB"; const string database = "shopping_sample"; var connectionString = $"Data Source={host};Initial Catalog={database};Integrated Security=True;"; using var connection = new SqlConnection(connectionString); connection.Open(); var userId = 79; // Session["USERID"] var productId = 1001; // Session["CartPID"] var quantity = 1; var query = "select * from tblCart where UID = @UserId"; // look up the shopping cart for a specific user // warning 1: there could be many carts for the same user. so this will not work // warning 2: if the value is from the web ui, the user can modify it // and modify another users cart. so this is not ok var command = new SqlCommand(query, connection); command.Parameters.AddWithValue("@UserId", userId); var reader = command.ExecuteReader(); // does the shopping cart exists? if (reader.Read()) { decimal.TryParse(reader[8].ToString(), out var existingQuantity); // release the connection s it can be re-used further down reader.Dispose(); // if so, update quantity and sell price var updateSql = "UPDATE tblCart SET Qty = @Quantity WHERE PID = @ProductId"; // warning 1: since the cart already exists the original product will be overwritten. // i.e, adding an apple then a banana.. now the cart contains 2 bananas. so this will not work using var updateCommand = new SqlCommand { Connection = connection, CommandType = CommandType.Text, CommandText = updateSql }; updateCommand.Parameters.AddWithValue("@Quantity", existingQuantity + quantity); updateCommand.Parameters.AddWithValue("@ProductId", productId); updateCommand.ExecuteNonQuery(); } else { var cartId = 1; // Session["CartPID"] var sellPrice = 100.50M; // Session["myPSelPrice"] var productName = "Apple"; // Session["myPName"] var price = 9.30M; // Session["myPPrice"] var insertSql = "INSERT INTO [dbo].[tblCart]([UID],[PID],[PName],[PPrice],[PSelPrice],[Qty]) VALUES (@UserId, @ProductId, @ProductName, @ProductPrice, @ProductSellPrice, @Quantity)"; // warning 1: if the value is from the web ui, the user can modify it // and select his/hers own price etc. so this is not ok // release the connection s it can be re-used further down reader.Dispose(); using var insertCommand = new SqlCommand { Connection = connection, CommandType = CommandType.Text, CommandText = insertSql }; insertCommand.Parameters.AddWithValue("@UserId", userId); insertCommand.Parameters.AddWithValue("@ProductId", productId); insertCommand.Parameters.AddWithValue("@ProductName", productName); insertCommand.Parameters.AddWithValue("@ProductPrice", price); insertCommand.Parameters.AddWithValue("@ProductSellPrice", sellPrice); insertCommand.Parameters.AddWithValue("@Quantity", quantity); insertCommand.ExecuteNonQuery(); } } } }

ADO.NET

namespace DapperSample { using System; using Dapper; using Microsoft.Data.SqlClient; // using nuget package Dapper // using nuget package Microsoft.Data.SqlClient internal class Program { private static void Main() { Console.WriteLine("Dapper shopping sample."); const string host = "(LocalDB)\\MSSQLLocalDB"; const string database = "shopping_sample"; var connectionString = $"Data Source={host};Initial Catalog={database};Integrated Security=True;"; using var connection = new SqlConnection(connectionString); var userId = 78; // Session["USERID"] var productId = 1001; // Session["CartPID"] var quantity = 1; var query = "select * from tblCart where UID = @UserId"; // look up the shopping cart for a specific user // warning 1: there could be many carts for the same user. so this will not work // warning 2: if the value is from the web ui, the user can modify it // and modify another users cart. so this is not ok var cart = connection.QueryFirstOrDefault( query, new { UserId = userId }); // does the shopping cart exists? if (cart != null) { var updateSql = "UPDATE tblCart SET Qty = @Quantity WHERE PID = @ProductId"; // if so, update quantity and sell price // warning 1: since the cart already exists the original product will be overwritten. // i.e, adding an apple then a banana.. now the cart contains 2 bananas. so this will not work connection.Execute( updateSql, new { Quantity = cart.Qty + quantity, ProductId = productId }); } else { var cartId = 1; // Session["CartPID"] var sellPrice = 100.50M; // Session["myPSelPrice"] var productName = "Apple"; // Session["myPName"] var price = 9.30M; // Session["myPPrice"] var insertSql = "INSERT INTO [dbo].[tblCart]([UID],[PID],[PName],[PPrice],[PSelPrice],[Qty]) VALUES (@UserId, @ProductId, @ProductName, @ProductPrice, @ProductSellPrice, @Quantity)"; // warning 1: if the value is from the web ui, the user can modify it // and select his/hers own price etc. so this is not ok connection.Execute(insertSql, new { UserId = userId, ProductId = productId, ProductName = productName, ProductPrice = price, ProductSellPrice = sellPrice, Quantity = quantity }); } } } }

Dapper

namespace EFCoreSample { using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; // using nuget package Microsoft.EntityFrameworkCore.SqlServer // using nuget package Microsoft.Data.SqlClient internal class Program { private static void Main() { Console.WriteLine("Entity Framework Core shopping sample."); const string host = "(LocalDB)\\MSSQLLocalDB"; const string database = "shopping_sample"; var connectionString = $"Data Source={host};Initial Catalog={database};Integrated Security=True;"; var dbContextBuilder = new DbContextOptionsBuilder<ShoppingContext>(); dbContextBuilder.UseSqlServer(connectionString); using var db = new ShoppingContext(dbContextBuilder.Options); var userId = 77; // Session["USERID"] var productId = 1001; // Session["CartPID"] var quantity = 1; // look up the shopping cart for a specific user // warning 1: there could be many carts for the same user. so this will not work // warning 2: if the value is from the web ui, the user can modify it // and modify another users cart. so this is not ok var cart = db.Carts.FirstOrDefault(x => x.UserId == userId); // does the shopping cart exists? if (cart != null) { // if so, update quantity and sell price // warning 1: since the cart already exists the original product will be overwritten. // i.e, adding an apple then a banana.. now the cart contains 2 bananas. so this will not work cart.Quantity += quantity; cart.ProductId = productId; } else { var cartId = 1; // Session["CartPID"] var sellPrice = 100.50M; // Session["myPSelPrice"] var productName = "Apple"; // Session["myPName"] var price = 9.30M; // Session["myPPrice"] // warning 1: if the value is from the web ui, the user can modify it // and select his/hers own price etc. so this is not ok cart = new Cart { ProductId = productId, ProductName = productName, Price = price, SellPrice = sellPrice, Quantity = quantity, UserId = userId }; db.Add(cart); } db.SaveChanges(); } } public class ShoppingContext : DbContext { public ShoppingContext(DbContextOptions<ShoppingContext> options) : base(options) { // empty.. } public virtual DbSet<Cart> Carts { get; set; } } [Table("tblCart")] public class Cart { [Key] [Column("CartID")] public int Id { get; set; } [Column("UID")] public int UserId { get; set; } [Column("PID")] public int ProductId { get; set; } [Column("Qty")] public int Quantity { get; set; } [Column("PSelPrice")] public decimal SellPrice { get; set; } [Column("SubSAmount")] [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public decimal TotalSellPrice { get; set; } // note: product related data should be in its own product table [Column("PName")] public string ProductName { get; set; } [Column("PPrice")] public decimal Price { get; set; } [Column("SubPAmount")] [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public decimal TotalPrice { get; set; } } }

EntityFramework
Permalänk

Här är en variant med Entity Framework som hanterar flera carts, med flera produker och använder en separat product tabell.

USE [shopping_sample2]
GO
/****** Object: Table [dbo].[CartItem] Script Date: 2020-12-13 23:05:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CartItem](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ProductId] [int] NOT NULL,
[Price] [decimal](18, 2) NOT NULL,
[Quantity] [int] NOT NULL,
[CartId] [uniqueidentifier] NULL,
[CartUserId] [uniqueidentifier] NULL,
CONSTRAINT [PK_CartItem] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Carts] Script Date: 2020-12-13 23:05:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Carts](
[Id] [uniqueidentifier] NOT NULL,
[UserId] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_Carts] PRIMARY KEY CLUSTERED
(
[Id] ASC,
[UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Products] Script Date: 2020-12-13 23:05:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Products](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ProductName] [nvarchar](max) NULL,
[Price] [decimal](18, 2) NOT NULL,
[SupplierPrice] [decimal](18, 2) NOT NULL,
CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Index [IX_CartItem_CartId_CartUserId] Script Date: 2020-12-13 23:05:28 ******/
CREATE NONCLUSTERED INDEX [IX_CartItem_CartId_CartUserId] ON [dbo].[CartItem]
(
[CartId] ASC,
[CartUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object: Index [IX_CartItem_ProductId] Script Date: 2020-12-13 23:05:28 ******/
CREATE NONCLUSTERED INDEX [IX_CartItem_ProductId] ON [dbo].[CartItem]
(
[ProductId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
ALTER TABLE [dbo].[CartItem] WITH CHECK ADD CONSTRAINT [FK_CartItem_Carts_CartId_CartUserId] FOREIGN KEY([CartId], [CartUserId])
REFERENCES [dbo].[Carts] ([Id], [UserId])
GO
ALTER TABLE [dbo].[CartItem] CHECK CONSTRAINT [FK_CartItem_Carts_CartId_CartUserId]
GO
ALTER TABLE [dbo].[CartItem] WITH CHECK ADD CONSTRAINT [FK_CartItem_Products_ProductId] FOREIGN KEY([ProductId])
REFERENCES [dbo].[Products] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[CartItem] CHECK CONSTRAINT [FK_CartItem_Products_ProductId]
GO
USE [master]
GO
ALTER DATABASE [shopping_sample2] SET READ_WRITE
GO

create_database_sql

namespace EFCoreSample2 { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.EntityFrameworkCore; // using nuget package Microsoft.EntityFrameworkCore.SqlServer // using nuget package Microsoft.Data.SqlClient internal class Program { private static void Main() { Console.WriteLine("Entity Framework Core shopping sample 2."); const string host = "(LocalDB)\\MSSQLLocalDB"; const string database = "shopping_sample2"; var connectionString = $"Data Source={host};Initial Catalog={database};Integrated Security=True;"; var dbContextBuilder = new DbContextOptionsBuilder<ShoppingContext>(); dbContextBuilder.UseSqlServer(connectionString); using var db = new ShoppingContext(dbContextBuilder.Options); // uncomment this to auto create the database if missing // warning: check your connection string first //db.Database.EnsureCreated(); // add sample products var apple = AddProduct(db, "Apple", 5.50M, 3M); var banana = AddProduct(db, "Banana", 12.20M, 6.76M); var quantity = 1; // note: use hard-coded guids to test update of carts var userId = Guid.NewGuid(); // Session["USERID"] var cartId = Guid.NewGuid(); // Session["CartPID"] // purchase the apple var productId = apple.Id; // Session["CartPID"] // look up the shopping cart for a specific user // and include all items var cart = db.Carts .Include(x => x.Items) .FirstOrDefault(x => x.UserId == userId && x.Id == cartId); // does the shopping cart exists? if (cart != null) { var existingCartItem = cart.Items.FirstOrDefault( x => x.ProductId == productId); // is the product type already ordered? if (existingCartItem != null) { // if so, update only quantity existingCartItem.Quantity += quantity; } else { var item = CreateCartItem( db, productId, quantity); // add the new item to the cart cart.Items.Add(item); } db.SaveChanges(); } else { cart = new Cart { Id = Guid.NewGuid(), UserId = userId }; var item = CreateCartItem( db, productId, quantity); // add the new item to the cart cart.Items.Add(item); db.Add(cart); } db.SaveChanges(); ShowCarts(db); } private static void ShowCarts(ShoppingContext db) { // get all carts with all items and its product var carts = db.Carts .Include(x => x.Items) .ThenInclude(x=> x.Product) .ToList(); foreach (var cart in carts) { Console.WriteLine($"cart {cart.Id} contains:"); foreach (var item in cart.Items) { Console.WriteLine($"\t item: {item.Product.ProductName}, qty: {item.Quantity}, tot.price: {item.Price*item.Quantity}"); } } } private static Product AddProduct( ShoppingContext db, string productName, decimal price, decimal supplierPrice) { var existingProduct = db.Products.FirstOrDefault(x => x.ProductName == productName); if (existingProduct != null) { return existingProduct; } var product = new Product { ProductName = productName, Price = price, SupplierPrice = supplierPrice }; db.Products.Add(product); db.SaveChanges(); return product; } private static CartItem CreateCartItem( ShoppingContext db, int productId, int quantity) { // look up the product price to be added to the cart var product = db.Products .Where(x => x.Id == productId) .Select(x => new { x.Price }) .FirstOrDefault(); if (product == null) { throw new Exception("Product does not exists."); } var item = new CartItem { Price = product.Price, ProductId = productId, Quantity = quantity }; return item; } } public class ShoppingContext : DbContext { public ShoppingContext(DbContextOptions<ShoppingContext> options) : base(options) { // empty.. } public virtual DbSet<Cart> Carts { get; set; } public virtual DbSet<Product> Products { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Cart>(entity => { // make a composite key so we can have multiple shopping carts at the same time // for a specific user (multiple tabs opened?) entity.HasKey(e => new { e.Id, e.UserId }); }); } } public class Cart { // note: make both id and cart id guid // so they cannot be guessed public Guid Id { get; set; } public Guid UserId { get; set; } public ICollection<CartItem> Items { get; set; } = new List<CartItem>(); } public class CartItem { public int Id { get; set; } public int ProductId { get; set; } public Product Product { get; set; } public decimal Price { get; set; } public int Quantity { get; set; } } public class Product { public int Id { get; set; } public string ProductName { get; set; } public decimal Price { get; set; } public decimal SupplierPrice { get; set; } } }

entity_framework_extended
Permalänk
Medlem

Måste ge dig cred @zoomster2 för vettigt och förklarande svar!

Till ts:
Entity framework är riktigt schysst men att skriva en del sql själv är också lärorikt istället för att hantera objekt som man gör i entityframework. Väljer du att skriva querys själv så tänk på sql-injection som flera här har påpekat.

Visa signatur

"Happiness is only real when shared"

Permalänk
Medlem
Skrivet av zoomster2:

Här är en variant med Entity Framework som hanterar flera carts, med flera produker och använder en separat product tabell.

Oj, Det var mycket att gå igenom! Jag ska titta närmare på det i morgon! Jag satt hela dagen men att försöka lösa det och kommit så här långt

protected void btnAddtoCart_Click(object sender, EventArgs e) { Int64 PID = Convert.ToInt64(Request.QueryString["PID"]); using (SqlConnection con = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("select * from tblCart where PID='" + PID + "'", con)) { cmd.CommandType = CommandType.Text; using (SqlDataAdapter sda = new SqlDataAdapter(cmd)) { DataTable dt = new DataTable(); sda.Fill(dt); if (dt.Rows.Count > 0) { Int64 updateQty = Convert.ToInt64(dt.Rows[0][8].ToString()); Int64 UserID = 0; Int64.TryParse((String)Session["Username"], out UserID); using (SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["RayOfbDB"].ConnectionString)) { SqlCommand cmd1 = new SqlCommand("UPDATE tblCart SET Qty=@Quantity WHERE PID=@CartPID", con1); cmd1.Connection = con1; cmd1.Parameters.Add("@Quantity", SqlDbType.Int).Value = updateQty + 1; cmd1.Parameters.Add("@CartPID", SqlDbType.Int).Value = PID; con1.Open(); cmd1.ExecuteNonQuery(); } } else { Int64 UserID = 0; Int64.TryParse((String)Session["Username"], out UserID); using (SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["RayOfbDB"].ConnectionString)) { string sqlQuery = "insert into tblCart values (@UID,@PID,@PName,@PPrice,@PSelPrice,@Qty)"; SqlCommand Cmd2 = new SqlCommand(sqlQuery, con2); Cmd2.Connection = con2; Cmd2.Parameters.Add("@UID", SqlDbType.Int).Value = UserID; Cmd2.Parameters.Add("@PID", SqlDbType.Int).Value = CartPID; Cmd2.Parameters.Add("@PName", SqlDbType.NVarChar, -1).Value = myPName; Cmd2.Parameters.Add("@PPrice", SqlDbType.Money).Value = myPPrice; Cmd2.Parameters.Add("@PSelPrice", SqlDbType.Money).Value = myPSelPrice; Cmd2.Parameters.Add("@Qty", SqlDbType.Int).Value = "1"; con.Open(); Int64 CartID = Convert.ToInt64(Cmd2.ExecuteScalar()); } } } } } }

Det error som jag får nu är att den inte "hittar" CartPID, myPName etc....
Att det ska var så bökigt att fixa en add to cart knapp! haha
Man lär sig sjukt mycket dock. Började med SQL för 3 veckor sedan så allt är ganska nytt än!
Tack för långa svar iaf! ska kolla på det i morgon när hjärnan är utvilad.