I have no clue why I get an exception. It says that the reader got closed before I try to access it. Why is that so?
Here is the code:
//Load Projects from SQL Server (nothing else)
public SPpowerPlantList loadProjectsFromServer(DateTime timestamp, string note, string sqlServer, string database)
{
SqlConnection sqlConnection = new SqlConnection(String.Format(#"Integrated Security=SSPI;server={0};Initial Catalog={1};", sqlServer, database));
sqlConnection.Open();
string selectstring = "SELECT * FROM [dbo].[tblSPpowerPlant]"; //(WHERE note {0} = " + note + " AND timestamp {1} = " + timestamp;
SqlCommand sqlSelectCommand = new SqlCommand(selectstring, sqlConnection);
sqlSelectCommand.CommandType = CommandType.Text;
sqlSelectCommand.CommandText = selectstring;
SqlDataReader reader;
SPpowerPlantList powerPlantList = new SPpowerPlantList();
reader = sqlSelectCommand.ExecuteReader();
//this line trowhs the exeption
while (reader.Read())
{
foreach (SPpowerPlant powerPlant in powerPlantList)
{
powerPlant.ID = reader.GetInt32(0);
powerPlant.projectName = reader.GetString(1).ToString();
powerPlant.location = reader.GetString(2);
powerPlant.shortName = reader.GetString(3);
powerPlant.numberOfWtgs = reader.GetInt32(4);
powerPlant.mwWtg = reader.GetDouble(5);
powerPlant.mwTotal = reader.GetDouble(6);
powerPlant.projectShareWeb = reader.GetDouble(7);
powerPlant.mwWeb = reader.GetDouble(8);
powerPlant.phase = reader.GetString(9);
powerPlant.phaseNumber = reader.GetString(10);
powerPlant.phaseDescription = reader.GetString(11);
powerPlant.projectProgress = reader.GetDouble(12);
powerPlant.mwDeveloped = reader.GetDouble(13);
powerPlant.projectManager = reader.GetString(14);
powerPlant.spaceUrl = reader.GetString(15);
powerPlant.country = reader.GetString(16);
powerPlant.technology = reader.GetString(17);
powerPlant.state = reader.GetString(18);
powerPlant.allPermits = reader.GetDateTime(19);
powerPlant.cod = reader.GetDateTime(20);
powerPlant.stateSince = reader.GetDateTime(21);
powerPlant.spID = reader.GetInt32(22);
powerPlant.currency = reader.GetString(23);
powerPlant.possibleWtgTypes = reader.GetString(24);
powerPlant.hubHeight = reader.GetString(25);
powerPlant.visibility = reader.GetString(26);
powerPlant.templateName = reader.GetString(27);
powerPlantList.Add(powerPlant);
}
reader.Dispose();
sqlConnection.Close();
}
return powerPlantList;
}
Here is the exception (google translate):
Invalid attempt to Read access because the data reader has been closed.
I tried it with google but had no luck. So any help would be great. Thanks for your time.
BTW Sorry for my english not my native language but I work on it.
the code lines
reader.Dispose();
sqlConnection.Close();
are inside the while(reader.read()) loop.
Also, you better use using instead of calling Dispose() yourself.
public SPpowerPlantList loadProjectsFromServer(DateTime timestamp, string note, string sqlServer, string database)
{
using(var sqlConnection = new SqlConnection(String.Format(#"Integrated Security=SSPI;server={0};Initial Catalog={1};", sqlServer, database)))
{
sqlConnection.Open();
var selectstring = "SELECT * FROM [dbo].[tblSPpowerPlant]"; //(WHERE note {0} = " + note + " AND timestamp {1} = " + timestamp;
var sqlSelectCommand = new SqlCommand(selectstring, sqlConnection);
sqlSelectCommand.CommandType = CommandType.Text;
sqlSelectCommand.CommandText = selectstring;
SPpowerPlantList powerPlantList = new SPpowerPlantList();
using(var reader = sqlSelectCommand.ExecuteReader())
{
while (reader.Read())
{
foreach (SPpowerPlant powerPlant in powerPlantList)
{
powerPlant.ID = reader.GetInt32(0);
powerPlant.projectName = reader.GetString(1).ToString();
powerPlant.location = reader.GetString(2);
powerPlant.shortName = reader.GetString(3);
powerPlant.numberOfWtgs = reader.GetInt32(4);
powerPlant.mwWtg = reader.GetDouble(5);
powerPlant.mwTotal = reader.GetDouble(6);
powerPlant.projectShareWeb = reader.GetDouble(7);
powerPlant.mwWeb = reader.GetDouble(8);
powerPlant.phase = reader.GetString(9);
powerPlant.phaseNumber = reader.GetString(10);
powerPlant.phaseDescription = reader.GetString(11);
powerPlant.projectProgress = reader.GetDouble(12);
powerPlant.mwDeveloped = reader.GetDouble(13);
powerPlant.projectManager = reader.GetString(14);
powerPlant.spaceUrl = reader.GetString(15);
powerPlant.country = reader.GetString(16);
powerPlant.technology = reader.GetString(17);
powerPlant.state = reader.GetString(18);
powerPlant.allPermits = reader.GetDateTime(19);
powerPlant.cod = reader.GetDateTime(20);
powerPlant.stateSince = reader.GetDateTime(21);
powerPlant.spID = reader.GetInt32(22);
powerPlant.currency = reader.GetString(23);
powerPlant.possibleWtgTypes = reader.GetString(24);
powerPlant.hubHeight = reader.GetString(25);
powerPlant.visibility = reader.GetString(26);
powerPlant.templateName = reader.GetString(27);
powerPlantList.Add(powerPlant);
}
}
}
}
return powerPlantList;
}
If you remove that foreach part you can see the problem.
You check if the reader is open
you iterate over the powerplant list, by the way this is reassigning each powerPlant to the same record in the reader
You close and dispose of the reader
Now you check if it is open again at the top of the while which throws the exception
I believe you want to create a new list of SPpowerPlant objects from your reader. You should change your code to the following which does that and releases the reader. Note that you should wrap all your Disposable objects in using statements like with the reader below.
using(var reader = sqlSelectCommand.ExecuteReader()) // closes and disposes reader once it is out of scope
{
while (reader.Read())
{
var powerPlant = new SPpowerPlant();
powerPlant.templateName = reader.GetString(27);
//// rest of calls to populate your item
SPpowerPlantList.Add(powerPlant);
}
}
Related
I have a method for getting data out of my SQL Server database. I'm using a reader to get all the data. The problem is that the reader keeps reading and the application doesn't pop up. It is like an infinite loop or something.
public static List<Reservering> GetReserverings()
{
Reservering res = new Reservering();
using (var conn = new SqlConnection(ConnectionString))
{
conn.Open();
const string query = "select b.boekingid, k.naam, bk.incheckdatum, bk.uitcheckdatum, b.hotelid, b.aantal_gasten from boeking b join klant k on k.klantid = b.boekingid join boekingkamer bk on b.boekingid = bk.boekingid where bk.incheckdatum is not null and bk.uitcheckdatum is not null";
SqlCommand selectReserveringen = new SqlCommand(query, conn);
SqlDataReader reader = selectReserveringen.ExecuteReader();
while (reader.Read())
{
res.Id = (int)reader["boekingid"];
res.Naam = (string)reader["naam"];
res.Incheck_datum = (DateTime)reader["incheckdatum"];
res.Uitcheck_datum = (DateTime)reader["uitcheckdatum"];
res.Hotel = (int)reader["hotelid"];
res.Aantal_personen = (int)reader["aantal_gasten"];
}
reader.Close();
}
return GetReserverings();
}
Does anyone know how to fix this problem?
You've got an infinite recursion by calling the method itself at the end:
return GetReserverings();
You could've discovered this by setting a breakpoint in your method and stepping through your code.
You want to return a list of reservations instead:
var result = new List<Reservering>();
// your code...
return result;
And within your while() loop, you'd want to instantiate a new Reservering each iteration, and Add it to the result list.
You should create an instance of Reservering for each record read and store these instances in the List<Reservering>:
public static List<Reservering> GetReserverings() {
List<Reservering> result = new List<Reservering>();
using (var conn = new SqlConnection(ConnectionString)) {
conn.Open();
const string query =
#"select b.boekingid,
k.naam,
bk.incheckdatum,
bk.uitcheckdatum,
b.hotelid,
b.aantal_gasten
from boeking b join
klant k on k.klantid = b.boekingid join
boekingkamer bk on b.boekingid = bk.boekingid
where bk.incheckdatum is not null
and bk.uitcheckdatum is not null";
using (SqlCommand selectReserveringen = new SqlCommand(query, conn)) {
using (SqlDataReader reader = selectReserveringen.ExecuteReader()) {
while (reader.Read()) {
Reservering res = new Reservering();
result.Add(res);
res.Id = Convert.ToInt32(reader["boekingid"]);
res.Naam = Convert.ToString(reader["naam"]);
res.Incheck_datum = Convert.ToDateTime(reader["incheckdatum"]);
res.Uitcheck_datum = Convert.ToDateTime(reader["uitcheckdatum"]);
res.Hotel = Convert.ToInt32(reader["hotelid"]);
res.Aantal_personen = Convert.ToInt32(reader["aantal_gasten"]);
}
}
}
}
return result;
}
Edit: You can try to simplify while loop with a help of object initializing:
...
while (reader.Read()) {
result.Add(new Reservering() {
Id = Convert.ToInt32(reader["boekingid"]),
Naam = Convert.ToString(reader["naam"]),
Incheck_datum = Convert.ToDateTime(reader["incheckdatum"]),
Uitcheck_datum = Convert.ToDateTime(reader["uitcheckdatum"]),
Hotel = Convert.ToInt32(reader["hotelid"]),
Aantal_personen = Convert.ToInt32(reader["aantal_gasten"])
});
}
public static List<Reservering> GetReserverings()
{
List<Reserving> reservings = new List<Reservings>();
using (var conn = new SqlConnection(ConnectionString))
{
conn.Open();
const string query = "select b.boekingid, k.naam, bk.incheckdatum, bk.uitcheckdatum, b.hotelid, b.aantal_gasten from boeking b join klant k on k.klantid = b.boekingid join boekingkamer bk on b.boekingid = bk.boekingid where bk.incheckdatum is not null and bk.uitcheckdatum is not null";
SqlCommand selectReserveringen = new SqlCommand(query, conn);
SqlDataReader reader = selectReserveringen.ExecuteReader();
while (reader.Read())
{
Reservering res = new Reservering();
res.Id = (int)reader["boekingid"];
res.Naam = (string)reader["naam"];
res.Incheck_datum = (DateTime)reader["incheckdatum"];
res.Uitcheck_datum = (DateTime)reader["uitcheckdatum"];
res.Hotel = (int)reader["hotelid"];
res.Aantal_personen = (int)reader["aantal_gasten"];
reservings.add(res);
}
reader.Close();
}
return reservings;
}
When I am executing this, I am getting the following error:
"Invalid attempt to read when no data is present"
I have data in the database but still it is showing like this. Help me.
public ActionResult Index()
{
SqlConnection con = new SqlConnection(connec);
con.Open();
SqlCommand cmd = new SqlCommand("select Title,DateReleased,TheaterName,Name,PhoneNo,Price,userName from vwTicketBooking ", con);
using (SqlDataReader dr = cmd.ExecuteReader())
{
List<TicketBooking> results = new List<TicketBooking>();
while (dr.Read())
newItem = new TicketBooking();
newItem.Title = dr["Title"].ToString();
newItem.DateReleased = Convert.ToDateTime(dr["DateReleased"]);
newItem.TheaterName = dr["TheaterName"].ToString();
newItem.Name = dr["Name"].ToString();
newItem.PhoneNo = dr["PhoneNo"].ToString();
newItem.Price = Convert.ToInt32(dr["Price"]);
newItem.userName = dr["userName"].ToString();
results.Add(newItem);
return View(results);
}
}
I think you need to use {} with your while statement because your code works like;
while (dr.Read())
{
newItem = new TicketBooking();
}
newItem.Title = dr["Title"].ToString();
newItem.DateReleased = Convert.ToDateTime(dr["DateReleased"]);
newItem.TheaterName = dr["TheaterName"].ToString();
...
and after last iteration, your reader will be after the last line, and there is no data to read it. Use it like;
while (dr.Read())
{
newItem = new TicketBooking();
newItem.Title = dr["Title"].ToString();
newItem.DateReleased = Convert.ToDateTime(dr["DateReleased"]);
newItem.TheaterName = dr["TheaterName"].ToString();
...
...
}
Also use using statement with SqlConnection and SqlCommand as well to dispose them automatically.
You are missing the enclosing brackets for your while loop. Your code in effect is only looping the single line newItem = new TicketBooking(); and when the reader finishes reading, you are attempting to use it again by saying newItem.Title = dr["Title"].ToString(); which is giving you the exception as there is nothing to read any further.
while (dr.Read())
{
newItem = new TicketBooking();
newItem.Title = dr["Title"].ToString();
newItem.DateReleased = Convert.ToDateTime(dr["DateReleased"]);
newItem.TheaterName = dr["TheaterName"].ToString();
newItem.Name = dr["Name"].ToString();
newItem.PhoneNo = dr["PhoneNo"].ToString();
newItem.Price = Convert.ToInt32(dr["Price"]);
newItem.userName = dr["userName"].ToString();
results.Add(newItem);
}
return View(results);
Although everything is correct, but data selection process is very slow in my Application, while retriving data from access .mdb file. Is there any idea that data can be accessed fast. Is there any mechanism??
This below code Runs when Button Clicked .
public class GetData {
OleDbConnection con = new OleDbConnection(DatabseConnection.ConnectionStringAccessDatabase);
public string lblPolicyNumber, lblInsuredName, lblIssuedDatePolicy, lblStatusPolicy,
lblModalPremium, lblDueDate, lblNextDueDate, lblAgentCode,
lblMode, lblType1, lblAmount1, lblDate1, lblPremAmt1,
lblDueDate1, lbPaidDate1, lblPremAmt2, lblDueDate2,
lblPaidDate2, lblPremAmt3, lbDueDate3, lblPadiDate3,
lblOwnersName, lblOwnersCode, lblAddress1, lblAddress2,
lblPlan, lblCoverageAmt, lblSex, lblBirthDate, lblAge,
lblAutomaticPrmloan, lblAPLCount, lblLoanType, lblLoanPrincipleamt,
lblLoanDate, lblRatedNotRated, lblUnderWritingApproved , LateFee,
TotalAmountDue, AmountInDeposit, NetPayableAmount, Overdueprem,
CurrentPremiumDue, lblPMFlastUpdated = null;
public void getData(string policyNumber)
{
try
{
con.Open();
}
catch { MessageBox.Show("Please Download the File From the Server, Or Contact IT Department"); }
OleDbCommand cmd = con.CreateCommand();
cmd.CommandText = "(Select capolnum, cainame, iss_dte, castatus, mod_prm, due_dte1, nxt_due, agent_code, cabmode, casustyp1, casusamt1, casusdate1, chbldpm1, pd_dte1, chbldpm2, due_dte2, pd_dte2, chbldpm3, due_dte3, pd_dte3 , caoname, ocode, Addr1, addr2, plan, cbcovamt, cbsex, birth_dte, cbissage, apl, as400_cl_aplcnt, as400_cl_lntype, as400_cl_lnprinc, apl_date, cstype, approved FROM agy_pmf where capolnum ='" + policyNumber + "' )";
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
SetData.lblPolicyNumber = lblPolicyNumber = dr.GetValue(0).ToString();
SetData.lblInsuredName = lblInsuredName = dr.GetValue(1).ToString();
lblIssuedDatePolicy = dr.GetValue(2).ToString();
lblStatusPolicy = dr.GetValue(3).ToString();
lblModalPremium = dr.GetValue(4).ToString();
lblDueDate = dr.GetValue(6).ToString();
lblNextDueDate = dr.GetValue(6).ToString();
lblAgentCode = dr.GetValue(7).ToString();
SetData.lblMode = lblMode = dr.GetValue(8).ToString();
lblType1 = dr.GetValue(9).ToString();
lblAmount1 = dr.GetValue(10).ToString();
lblDate1 = dr.GetValue(11).ToString();
lblPremAmt1 = dr.GetValue(12).ToString();
lblDueDate1 = dr.GetValue(5).ToString();
lbPaidDate1 = dr.GetValue(13).ToString();
lblPremAmt2 = dr.GetValue(14).ToString();
lblDueDate2 = dr.GetValue(15).ToString();
lblPaidDate2 = dr.GetValue(16).ToString();
lblPremAmt3 = dr.GetValue(17).ToString();
lbDueDate3 = dr.GetValue(18).ToString();
lblPadiDate3 = dr.GetValue(19).ToString();
lblOwnersName = dr.GetValue(20).ToString();
lblOwnersCode = dr.GetValue(21).ToString();
lblAddress1 = dr.GetValue(22).ToString();
lblAddress2 = dr.GetValue(23).ToString();
lblPlan = dr.GetValue(24).ToString();
lblCoverageAmt = dr.GetValue(25).ToString();
lblSex = dr.GetValue(26).ToString();
lblBirthDate = dr.GetValue(27).ToString();
lblAge = dr.GetValue(28).ToString();
lblAutomaticPrmloan = dr.GetValue(29).ToString();
lblAPLCount = dr.GetValue(30).ToString();
lblLoanType = dr.GetValue(31).ToString();
lblLoanPrincipleamt = dr.GetValue(32).ToString();
lblLoanDate = dr.GetValue(33).ToString();
lblRatedNotRated = dr.GetValue(34).ToString();
lblUnderWritingApproved = dr.GetValue(35).ToString();
con.Close();
}
}}
I submit the query, and it doesn't throw an exception, and it does write to the database, but not what I want. For some reason it doesn't touch anything apart from the first thing I tell the query, and sets that to a 0.
Here is my code:
public static int UpdateTagDefinition(Dictionary<string, object> sqlQueryParams)
{
MySqlCommand query = new MySqlCommand();
query.CommandText = "UPDATE `windows_dev` SET `name` = #name AND `desc_short` = #desc_short AND `desc_long` = #desc_long AND `tags` = #tags AND `image_title` = #image_title AND `images` = #images AND `release_date` = #release_date AND `update_date` = #update_date AND `is_on_sourcecontrol` = #is_on_sourcecontrol AND `sourcecontrol_type` = #sourcecontrol_type AND `sourcecontrol_uri` = #sourcecontrol_uri AND `download_uri` = #download_uri AND `project_uri` = #project_uri AND `source_uri` = #source_uri AND `is_public` = #is_public WHERE `DID` = #did;";
query.Parameters.Clear();
foreach(var sqlParam in sqlQueryParams)
{
query.Parameters.AddWithValue("#" + sqlParam.Key.ToString(), sqlParam.Value);
}
return Connector.RunSQLUpdateQuery(query);
}
public static int RunSQLUpdateQuery(MySqlCommand query)
{
try
{
MySqlConnection cnx = new MySqlConnection(ConfigurationManager.ConnectionStrings["******"].ConnectionString);
// Connect to News Database and get recent article
query.Connection = cnx;
cnx.Open();
MySqlDataReader Reader;
Reader = query.ExecuteReader();
cnx.Close();
return 1;
}
catch
{
return 2;
}
}
And the place where I set the SQL Params;
Dictionary<string, object> sqlQueryParams = new Dictionary<string, object>();
sqlQueryParams.Add("name", Request.Form["name"]);
sqlQueryParams.Add("desc_short", Request.Form["desc_short"]);
sqlQueryParams.Add("desc_long", Request.Form["desc_long"]);
sqlQueryParams.Add("tags", TagDefinitions.TagDefinitionsToSQL(TagDefinitions.GetTagDefinitionIdentsFromList((List<string>)JsonConvert.DeserializeObject(Request.Form["tags"], typeof(List<string>)))));
sqlQueryParams.Add("image_title", Request.Form["image_title"]);
sqlQueryParams.Add("images", Request.Form["images"]);
sqlQueryParams.Add("release_date", Request.Form["release_date"]);
sqlQueryParams.Add("update_date", Request.Form["update_date"]);
sqlQueryParams.Add("is_on_sourcecontrol", Request.Form["is_on_sourcecontrol"]);
sqlQueryParams.Add("sourcecontrol_type", Request.Form["sourcecontrol_type"]);
sqlQueryParams.Add("sourcecontrol_uri", Request.Form["sourcecontrol_uri"]);
sqlQueryParams.Add("download_uri", Request.Form["download_uri"]);
sqlQueryParams.Add("project_uri", Request.Form["project_uri"]);
sqlQueryParams.Add("source_uri", Request.Form["source_uri"]);
sqlQueryParams.Add("is_public", Request.Form["is_public"]);
sqlQueryParams.Add("did", int.Parse(Request.Form["did"]));
when you want to update multiple columns, use COMMA instead of AND
query.CommandText = #"UPDATE `windows_dev`
SET `name` = #name,
`desc_short` = #desc_short,
... other columns .....
`is_public` = #is_public
WHERE `DID` = #did";
I'm a rookie, as evinced by my question, and I'm using a datareader to find the rows associated with a certain subId value. I used a while(dr.read) loop and nested a switch case statement with other readers in each case (code below), but I threw the exception "already an open data reader associated with this command which must be closed first." Is there a way to store the results of the first datareader (the relevant rows where subId = x) in an array, or list, and then close that reader before I enter my switch statement? (I understand what an array is to the extent that I imagine it would work, but I haven't a clue what the syntax would look like).
string viewQuery = "SELECT ProductId FROM SubmissionProducts WHERE SubmissionId =" + x;
using (SqlCommand viewcmd = new SqlCommand(viewQuery, editConn))
{
SqlDataReader dr = viewcmd.ExecuteReader();
while (dr.Read())
{
switch(dr.GetInt32(0))
{
case 1:
PanelEplShow.Visible = true;
using (SqlCommand eplviewcmd = new SqlCommand(epl, editConn))
{
SqlDataReader epldr = eplviewcmd.ExecuteReader();
epldr.Read();
LblEplShowEntity.Text = epldr.GetString(0);
LblEplShowTotalEmpl.Text = epldr.GetInt32(1).ToString();
LblEplShowCalEmpl.Text = epldr.GetInt32(2).ToString();
LblEplShowMichEmpl.Text = epldr.GetInt32(3).ToString();
LblEplShowNyEmpl.Text = epldr.GetInt32(4).ToString();
LblEplShowNjEmpl.Text = epldr.GetInt32(5).ToString();
LblEplShowPrimEx.Text = epldr.GetInt32(6).ToString();
LblEplShowLim.Text = epldr.GetInt32(7).ToString();
LblEplShowPrem.Text = epldr.GetInt32(8).ToString();
LblEplShowWage.Text = epldr.GetInt32(9).ToString();
LblEplShowInvestCost.Text = epldr.GetInt32(10).ToString();
epldr.Close();
}
break;
case 2:
PanelProfShow.Visible = true;
using (SqlCommand profcmd1 = new SqlCommand(prof, editConn))
{
SqlDataReader profdr = profcmd1.ExecuteReader();
profdr.Read();
LblProfShowPrimEx.Text = profdr.GetInt32(0).ToString();
LblProfShowType.Text = profdr.GetInt32(1).ToString();
LblProfShowLim.Text = profdr.GetInt32(2).ToString();
LblProfShowRetention.Text = profdr.GetInt32(3).ToString();
LblProfShowAtt.Text = profdr.GetInt32(4).ToString();
LblProfShowPrem.Text = profdr.GetInt32(5).ToString();
LblProfShowSublim.Text = profdr.GetInt32(5).ToString();
LblProfShowEntity.Text = profdr.GetInt32(6).ToString();
profdr.Close();
}
break;
case 3:
PanelCrimeShow.Visible = true;
using (SqlCommand crimcmd = new SqlCommand(crim, editConn))
{
SqlDataReader crimdr = crimcmd.ExecuteReader();
crimdr.Read();
LblCrimeShowEntity.Text = crimdr.GetString(0);
LblCrimeShowEmpl.Text = crimdr.GetInt32(1).ToString();
LblCrimeShowPrimEx.Text = crimdr.GetInt32(2).ToString();
LblCrimeShowLimA.Text = crimdr.GetInt32(3).ToString();
LblCrimeShowDedA.Text = crimdr.GetInt32(4).ToString();
LblCrimeShowPremA.Text = crimdr.GetInt32(5).ToString();
LblCrimeShowLimB.Text = crimdr.GetInt32(6).ToString();
LblCrimeShowDedB.Text = crimdr.GetInt32(7).ToString();
LblCrimeShowPremB.Text = crimdr.GetInt32(8).ToString();
crimdr.Close();
}
break;
case 4:
PanelFidShow.Visible = true;
using (SqlCommand fidcmd = new SqlCommand(fid, editConn))
{
SqlDataReader fiddr = fidcmd.ExecuteReader();
fiddr.Read();
LblFidShowEntity.Text = fiddr.GetString(0);
LblFidShowPrimEx.Text = fiddr.GetInt32(1).ToString();
LblFidShowLim.Text = fiddr.GetInt32(2).ToString();
LblFidShowSir.Text = fiddr.GetInt32(3).ToString();
LblFidShowAtt.Text = fiddr.GetInt32(4).ToString();
LblFidShowPrem.Text = fiddr.GetInt32(5).ToString();
LblFidShowSublim.Text = fiddr.GetInt32(6).ToString();
fiddr.Close();
}
break;
case 5:
PanelNotShow.Visible = true;
using (SqlCommand notcmd = new SqlCommand(not, editConn))
{
SqlDataReader notdr = notcmd.ExecuteReader();
notdr.Read();
LblNotShowPrimEx.Text = notdr.GetInt32(0).ToString();
LblNotShowCov.Text = notdr.GetInt32(1).ToString();
LblNotShowSharedLim.Text = notdr.GetInt32(2).ToString();
LblNotShowTradLim.Text = notdr.GetInt32(3).ToString();
LblNotShowTradSir.Text = notdr.GetInt32(4).ToString();
LblNotShowEplLim.Text = notdr.GetInt32(5).ToString();
LblNotShowEplSir.Text = notdr.GetInt32(6).ToString();
LblNotShowEplPrem.Text = notdr.GetInt32(7).ToString();
LblNotShowSublim.Text = notdr.GetInt32(8).ToString();
notdr.Close();
}
break;
case 6:
PanelPrivShow.Visible = true;
using (SqlCommand privcmd = new SqlCommand(priv, editConn))
{
SqlDataReader privdr = privcmd.ExecuteReader();
privdr.Read();
LblPrivShowPrimEx.Text = privdr.GetInt32(0).ToString();
LblPrivShowSharedLim.Text = privdr.GetInt32(1).ToString();
LblPrivShowTradLim.Text = privdr.GetInt32(2).ToString();
LblPrivShowTradAtt.Text = privdr.GetInt32(3).ToString();
LblPrivShowTradSir.Text = privdr.GetInt32(4).ToString();
LblPrivShowTradPrem.Text = privdr.GetInt32(5).ToString();
LblPrivShowEplLim.Text = privdr.GetInt32(6).ToString();
LblPrivShowEplSir.Text = privdr.GetInt32(7).ToString();
LblPrivShowEplAtt.Text = privdr.GetInt32(8).ToString();
LblPrivShowEplPrem.Text = privdr.GetInt32(9).ToString();
LblPrivShowEplWage.Text = privdr.GetInt32(10).ToString();
LblPrivShowEplSublim.Text = privdr.GetInt32(11).ToString();
LblPrivShowFidLim.Text = privdr.GetInt32(12).ToString();
LblPrivShowFidSir.Text = privdr.GetInt32(13).ToString();
LblPrivShowFidAtt.Text = privdr.GetInt32(14).ToString();
LblPrivShowFidPrem.Text = privdr.GetInt32(15).ToString();
LblPrivShowFidSublim.Text = privdr.GetInt32(16).ToString();
privdr.Close();
}
break;
case 7:
PanelPubShow.Visible = true;
using (SqlCommand pubcmd = new SqlCommand(pub, editConn))
{
SqlDataReader pubdr = pubcmd.ExecuteReader();
pubdr.Read();
LblPubShowMark.Text = pubdr.GetInt32(0).ToString();
LblPubShowTick.Text = pubdr.GetInt32(1).ToString();
LblPubShowTrad.Text = pubdr.GetInt32(2).ToString();
LblPubShowDic.Text = pubdr.GetInt32(3).ToString();
LblPubShowLim.Text = pubdr.GetInt32(4).ToString();
LblPubShowSecSir.Text = pubdr.GetInt32(5).ToString();
LblPubShowAllSir.Text = pubdr.GetInt32(6).ToString();
LblPubShowPrem.Text = pubdr.GetInt32(7).ToString();
LblPubShowPrimEx.Text = pubdr.GetInt32(8).ToString();
LblPubShowAtt.Text = pubdr.GetInt32(9).ToString();
LblPubShowSublim.Text = pubdr.GetInt32(10).ToString();
pubdr.Close();
}
break;
default:
break;
}
}
dr.Close();`
Load it into a DataTable.
SqlDataReader pubdr = pubcmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(pubdr);
To expand on the comments:
foreach (DataRow dr in dt.Rows)
{
LblEplShowEntity.Text = dr["FIELDNAME"].ToString();
//...
}
Load a DataTable instead, which internally is a persisted DataReader anyway
For a DataReader you consume, use, discard. This is the nature of DataReaders. If you want the data to hang around, you'd use a DataTable. Simple, but a good rule of thumb.
Assuming SubmissionId is unique in the table SubmissionProducts , you don't need to use a data reader for the query. You can instead use the ExecuteScalar method of the command object.
If you want to get an array of all the collumn values in the current row from a DataReader you can use the GetValues method like this:
SqlDataReader reader; // assumming the data reader is already opened
object[] columns = new object[reader.FieldCount];
reader.GetValues(columns);// columns now contains all the values from the curent row
I found I had to adjust something in my connection string. I don't know if it's a .Net glitch or whether it's just a necessary adjustment when using nested readers, but I had to add MultipleActiveResultSets="true" to my stored connection string. Afterwards, everything worked properly, with no need for a datatable. Many thanks to everyone who answered. While I'm sure the answers above could also have worked, in case this question is of any utility to someone in the future, I'm posting the full code to show what worked for me. Word of caution: if you're new enough to coding to need this post, PARAMETERIZE your queries. This site was a training project where I was instructed to avoid parameterizing in the interest of learning other things first, but it's paramount. Bobby tables ftw.
Here's the code.
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class View : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string x = Request.QueryString["SubmissionId"];
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
string editCustQuery = "SELECT CustName, SicNaic, CustCity, CustAdd, CustState, CustZip FROM Customer WHERE SubId =" + x;
string editBroQuery = "SELECT BroName, BroAdd, BroCity, BroState, BroZip, EntityType FROM Broker WHERE SubId =" + x;
string editSubQuery = "SELECT Coverage, CurrentCoverage, PrimEx, Retention, EffectiveDate, Commission, Premium, Comments FROM Submission WHERE SubmissionId =" + x;
string epl = "SELECT Entity, Employees, CA, MI, NY, NJ, Primex, EplLim, EplSir, Premium, Wage, Sublim FROM EPL WHERE SubmissionId =" + x;
string prof = "SELECT Primex, EO, Limit, Retention, Att, Prem, Sublim, Entity FROM ProfessionalEO WHERE SubmissionId =" + x;
string crim = "SELECT Entity, Employees, PrimEx, LimA, DedA, PremA, LimitB, DedB, PremB FROM CrimeFidelity WHERE SubmissionId =" + x;
string fid = "SELECT Entity, PrimEx, Limit, SIR, Att, Premium, Sublim FROM Fiduciary WHERE SubmissionId =" + x;
string not = "SELECT PrimEx, Coverage, SharedSepLim, TradLim, TradDoSir, EplLim, EplSir, EplPrem, EplSublim FROM NotProfit WHERE SubmissionId =" + x;
string priv = "SELECT Primex, SharedSepLim, TradLim, TradAtt, TradDoSir, TradPrem, EplLim, EplSir, EplAtt, EplWage, EplPrem, EplInvest, FidLim, FidSir, FidAtt, FidPrem, FidSublim FROM PrivateCompany WHERE SubmissionId =" + x;
string pub = "SELECT Market, Ticker, TradABC, DIC, Limit, SecuritiesSir, OtherSir, Premium, PrimEx, Att, Sublim FROM PublicDO WHERE SubmissionId =" + x;
using (SqlConnection editConn = new SqlConnection(connectionString))
{
editConn.Open();
using (SqlCommand CustCommand = new SqlCommand(editCustQuery, editConn))
{
SqlDataReader dr = CustCommand.ExecuteReader();
dr.Read();
LblCustName.Text = dr.GetString(0);
LblSicNaic.Text = dr.GetString(1);
LblCustCity.Text = dr.GetString(2);
LblCustAddress.Text = dr.GetString(3);
LblCustState.Text = dr.GetString(4);
LblCustZip.Text = dr.GetInt32(5).ToString();
dr.Close();
}
using (SqlCommand BroCommand = new SqlCommand(editBroQuery, editConn))
{
SqlDataReader dr = BroCommand.ExecuteReader();
dr.Read();
LblBroName.Text = dr.GetString(0);
LblBroAddress.Text = dr.GetString(1);
LblBroCity.Text = dr.GetString(2);
LblBroState.Text = dr.GetString(3);
LblBroZip.Text = dr.GetInt32(4).ToString();
LblEntity.Text = dr.GetString(5);
dr.Close();
}
using (SqlCommand SubCommand = new SqlCommand(editSubQuery, editConn))
{
SqlDataReader dr = SubCommand.ExecuteReader();
dr.Read();
LblCoverage.Text = dr.GetInt32(0).ToString();
LblCurrentCoverage.Text = dr.GetInt32(1).ToString();
LblPrimEx.Text = dr.GetInt32(2).ToString();
LblRetention.Text = dr.GetInt32(3).ToString();
LblEffectDate.Text = dr.GetDateTime(4).ToString();
LblCommission.Text = dr.GetInt32(5).ToString();
LblPremium.Text = dr.GetInt32(6).ToString();
LblComments.Text = dr.GetString(7);
dr.Close();
HyperLink1.NavigateUrl = "~/ViewEdit.aspx?SubmissionId=" + x;
}
string viewQuery = "SELECT ProductId FROM SubmissionProducts WHERE SubmissionId =" + x;
SqlCommand viewcmd = new SqlCommand(viewQuery, editConn);
SqlDataReader drRows = viewcmd.ExecuteReader();
while (drRows.Read())
{
switch (drRows.GetInt32(0))
{
case 1:
PanelEplShow.Visible = true;
using (SqlCommand eplviewcmd = new SqlCommand(epl, editConn))
{
SqlDataReader epldr = eplviewcmd.ExecuteReader();
epldr.Read();
LblEplShowEntity.Text = epldr.GetString(0);
LblEplShowTotalEmpl.Text = epldr.GetInt32(1).ToString();
LblEplShowCalEmpl.Text = epldr.GetInt32(2).ToString();
LblEplShowMichEmpl.Text = epldr.GetInt32(3).ToString();
LblEplShowNyEmpl.Text = epldr.GetInt32(4).ToString();
LblEplShowNjEmpl.Text = epldr.GetInt32(5).ToString();
LblEplShowPrimEx.Text = epldr.GetInt32(6).ToString();
LblEplShowLim.Text = epldr.GetInt32(7).ToString();
LblEplShowSir.Text = epldr.GetInt32(8).ToString();
LblEplShowPrem.Text = epldr.GetInt32(9).ToString();
LblEplShowWage.Text = epldr.GetInt32(10).ToString();
LblEplShowInvestCost.Text = epldr.GetInt32(11).ToString();
epldr.Close();
}
break;
case 2:
PanelProfShow.Visible = true;
using (SqlCommand profcmd = new SqlCommand(prof, editConn))
{
SqlDataReader profdr = profcmd.ExecuteReader();
profdr.Read();
LblProfShowPrimEx.Text = profdr.GetInt32(0).ToString();
LblProfShowType.Text = profdr.GetString(1);
LblProfShowLim.Text = profdr.GetInt32(2).ToString();
LblProfShowRetention.Text = profdr.GetInt32(3).ToString();
LblProfShowAtt.Text = profdr.GetInt32(4).ToString();
LblProfShowPrem.Text = profdr.GetInt32(5).ToString();
LblProfShowSublim.Text = profdr.GetInt32(6).ToString();
LblProfShowEntity.Text = profdr.GetString(7);
profdr.Close();
}
break;
case 3:
PanelCrimeShow.Visible = true;
using (SqlCommand crimcmd = new SqlCommand(crim, editConn))
{
SqlDataReader crimdr = crimcmd.ExecuteReader();
crimdr.Read();
LblCrimeShowEntity.Text = crimdr.GetString(0);
LblCrimeShowEmpl.Text = crimdr.GetInt32(1).ToString();
LblCrimeShowPrimEx.Text = crimdr.GetInt32(2).ToString();
LblCrimeShowLimA.Text = crimdr.GetInt32(3).ToString();
LblCrimeShowDedA.Text = crimdr.GetInt32(4).ToString();
LblCrimeShowPremA.Text = crimdr.GetInt32(5).ToString();
LblCrimeShowLimB.Text = crimdr.GetInt32(6).ToString();
LblCrimeShowDedB.Text = crimdr.GetInt32(7).ToString();
LblCrimeShowPremB.Text = crimdr.GetInt32(8).ToString();
crimdr.Close();
}
break;
case 4:
PanelFidShow.Visible = true;
using (SqlCommand fidcmd = new SqlCommand(fid, editConn))
{
SqlDataReader fiddr = fidcmd.ExecuteReader();
fiddr.Read();
LblFidShowEntity.Text = fiddr.GetString(0);
LblFidShowPrimEx.Text = fiddr.GetInt32(1).ToString();
LblFidShowLim.Text = fiddr.GetInt32(2).ToString();
LblFidShowSir.Text = fiddr.GetInt32(3).ToString();
LblFidShowAtt.Text = fiddr.GetInt32(4).ToString();
LblFidShowPrem.Text = fiddr.GetInt32(5).ToString();
LblFidShowSublim.Text = fiddr.GetInt32(6).ToString();
fiddr.Close();
}
break;
case 5:
PanelNotShow.Visible = true;
using (SqlCommand notcmd = new SqlCommand(not, editConn))
{
SqlDataReader notdr = notcmd.ExecuteReader();
notdr.Read();
LblNotShowPrimEx.Text = notdr.GetInt32(0).ToString();
LblNotShowCov.Text = notdr.GetInt32(1).ToString();
LblNotShowSharedLim.Text = notdr.GetInt32(2).ToString();
LblNotShowTradLim.Text = notdr.GetInt32(3).ToString();
LblNotShowTradSir.Text = notdr.GetInt32(4).ToString();
LblNotShowEplLim.Text = notdr.GetInt32(5).ToString();
LblNotShowEplSir.Text = notdr.GetInt32(6).ToString();
LblNotShowEplPrem.Text = notdr.GetInt32(7).ToString();
LblNotShowSublim.Text = notdr.GetInt32(8).ToString();
notdr.Close();
}
break;
case 6:
PanelPrivShow.Visible = true;
using (SqlCommand privcmd = new SqlCommand(priv, editConn))
{
SqlDataReader privdr = privcmd.ExecuteReader();
privdr.Read();
LblPrivShowPrimEx.Text = privdr.GetInt32(0).ToString();
LblPrivShowSharedLim.Text = privdr.GetInt32(1).ToString();
LblPrivShowTradLim.Text = privdr.GetInt32(2).ToString();
LblPrivShowTradAtt.Text = privdr.GetInt32(3).ToString();
LblPrivShowTradSir.Text = privdr.GetInt32(4).ToString();
LblPrivShowTradPrem.Text = privdr.GetInt32(5).ToString();
LblPrivShowEplLim.Text = privdr.GetInt32(6).ToString();
LblPrivShowEplSir.Text = privdr.GetInt32(7).ToString();
LblPrivShowEplAtt.Text = privdr.GetInt32(8).ToString();
LblPrivShowEplPrem.Text = privdr.GetInt32(9).ToString();
LblPrivShowEplWage.Text = privdr.GetInt32(10).ToString();
LblPrivShowEplSublim.Text = privdr.GetInt32(11).ToString();
LblPrivShowFidLim.Text = privdr.GetInt32(12).ToString();
LblPrivShowFidSir.Text = privdr.GetInt32(13).ToString();
LblPrivShowFidAtt.Text = privdr.GetInt32(14).ToString();
LblPrivShowFidPrem.Text = privdr.GetInt32(15).ToString();
LblPrivShowFidSublim.Text = privdr.GetInt32(16).ToString();
privdr.Close();
}
break;
case 7:
PanelPubShow.Visible = true;
using (SqlCommand pubcmd = new SqlCommand(pub, editConn))
{
SqlDataReader pubdr = pubcmd.ExecuteReader();
pubdr.Read();
LblPubShowMark.Text = pubdr.GetInt32(0).ToString();
LblPubShowTick.Text = pubdr.GetInt32(1).ToString();
LblPubShowTrad.Text = pubdr.GetInt32(2).ToString();
LblPubShowDic.Text = pubdr.GetString(3);
LblPubShowLim.Text = pubdr.GetInt32(4).ToString();
LblPubShowSecSir.Text = pubdr.GetInt32(5).ToString();
LblPubShowAllSir.Text = pubdr.GetInt32(6).ToString();
LblPubShowPrem.Text = pubdr.GetInt32(7).ToString();
LblPubShowPrimEx.Text = pubdr.GetInt32(8).ToString();
LblPubShowAtt.Text = pubdr.GetInt32(9).ToString();
LblPubShowSublim.Text = pubdr.GetInt32(10).ToString();
pubdr.Close();
}
break;
default:
break;
}
}
drRows.Close();
}
}
}