String + db table to fill values ​​in gridview

I have a row with prodIDs as "3, 16, 12" is it possible to map these ids to the product table in db and display data like name, price in gridview?

PS: im new for C # and asp.net!

thanks,

0


a source to share


2 answers


I can give you a simple SQL query that will return you what you want:

SELECT name, price FROM [product] WHERE ProdID IN (3,16,12)

      

but in order to do this safely and efficiently, it is best to know what you have and where that ids string comes from (how it is built).




Based on your comment, it looks like you are using Session (and ArrayList-ugh), if you are still on .Net 1.1 they are angry) as your shopping cart. Instead, you will move this to the database. Instead of putting every cart item in the session, there is a db table and every time the user selects an item, add that item to the shopping cart table. Then your sql query will look like this:

SELECT name, price 
FROM [product] 
WHERE ProdID IN 
    SELECT ProdID 
    FROM [ShoppingCart] 
    WHERE CartSession= @CurrentSessionID

      

+1


a source


Use some function to split delimited string into table:

Here's an example.

Then use the stored procedure like this:



CREATE PROCEDURE GetProductsByDelimitedString 
@myString nvarchar(max)
AS
BEGIN
select * from Products where ID in (select * from SplitFunction(@myString))
END

      

Then bind the gridview to the result of the stored procedure:

    string myString = "3,6,12";

    SqlConnection conn = GetSqlConnection();
    GridView gvw = GetGridView();
    SqlCommand cmd = new SqlCommand("GetProductsByDelimitedString", conn);

    cmd.CommandType = System.Data.CommandType.StoredProcedure;        
    cmd.Parameters.AddWithValue("@myString", myString);
    try
    {
        conn.Open();
        gvw.DataSource = cmd.ExecuteReader();
        gvw.DataBind();
        conn.Close();
    }
    catch
    {
        // something bad happened
    }

      

+1


a source







All Articles