user6592730 user6592730 - 1 year ago 67
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

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();
grdPolicyDetails.DataSource = dt;
Session["PolicyTable"] = dt;

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download