user6592730 user6592730 - 3 months ago 8
ASP.NET (C#) Question

How to get the values in a session to dataset using a foreach loop?

I have a session which includes a data table in it. Now i want to get each number and store it in the database using a

foreach
loop. I have tried a code. But it shows this error message. "


Cannot convert type 'char' to 'System.Web.UI.WebControls.ListItem'"


How can i do it?


Here is my code

protected void policyDetails()
{
DataSet ds = new DataSet();
string cellVal = "";

foreach (ListItem item in Session["PolicyTable"].ToString())
{
cellVal = item.ToString();
ds = db.insertPolicyDetails(cellVal);
}
}


This is how create the session

dr = dt.NewRow();
dr["Policy_No"] = txtPolicy.Text.Trim();
dt.Rows.Add(dr);
grdPolicyDetails.DataSource = dt;
grdPolicyDetails.DataBind();
Session["PolicyTable"] = dt;

Answer

This error is coming because you are iterating over the Session["PolicyTable"] as ListItem. Change this to DataRow. Also if the session variable contains the datatable, you will be iterating over rows which cant be a string. Even if it contains a single column, you should retreive its value as:

DataTable dtSessionTable = (DataTable)Session["PolicyTable"];

foreach (DataRow item in dtSessionTable.Rows)
{
    cellVal = item["Policy_No"].ToString();
    ds = db.insertPolicyDetails(cellVal);
}