Reputation: 620
I trying to read a data from a particular session variables called 'cart'. However, when i execute the method below, the output string is the following System.Collections.Generic.List
1[System.String]`, instead my desire goal is retrieve the product id data value (session 'cart').
protected void AddToCart_Click(object sender, EventArgs e)
{
var selectedProducts = GridView1.Rows.Cast<GridViewRow>()
.Where(row => ((CheckBox)row.FindControl("SelectedProducts")).Checked)
.Select(row => GridView1.DataKeys[row.RowIndex].Value.ToString()).ToList();
if (Session["Cart"] == null)
{
Session["Cart"] = selectedProducts;
}
else
{
List<String> cart = new List<String>();
cart = (List<string>)Session["Cart"];
foreach (var product in selectedProducts)
cart.Add(product);
Session["Cart"] = cart;
}
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("SelectedProducts");
if (cb.Checked)
cb.Checked = true;
{
// string data = (string)Session["Cart"];
List<string> cart = (List<string>)Session["Cart"];
Label1.Text = cart.ToString();
}
}
}
Any further advice, as to where I may be going wrong, would be most appreciated.
Many thanks.
Upvotes: 0
Views: 132
Reputation: 2294
List<T>.ToString()
has the following default implementation:
public virtual String ToString()
{
return GetType().ToString();
}
You need to provide your own implementation by overriding that (in a derived class, of course) if you want to use ToString()
in the manner you describe.
Edit: Assuming you don't have to use ToString()
there are several other options. Using Linq you can aggregate the list like so:
cart.Aggregate(String.Empty, (a, b) => a + ", " + b);
Or you can turn it into an Array
and use String.Join()
(as Rick suggests), or you can implement an extension method for IEnumerable<String>
or whatever suits your purposes.
Upvotes: 1