creating a search button - c#

I want to create a button on my c# form and when I type in a clients id or surname and I press the search button, it should display all his info on the c# form.
This is not working, a message box displays 'clientid' when the button is clicked.
Code in Class
public bool searchpersonDetails(string personid, string personname)
{
SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
conn.ConnectionString = "Data Source=pc101;Initial Catalog=REMITTANCE;User ID=sa;Password=mike";
conn.Open();
if (personid == null)
{
Fom1 frm = new Fom1();
frm.ShowDialog();
personid = client_id;
}
SqlCommand cmd = new SqlCommand();
string sqlQuery = null;
//sqlQuery = "select *,floor(datediff(curdate(),dateofbirth)/365) AS AGE from tblspersonaldetails where client_id='" + personid + "'";
sqlQuery = "select * from tblspersonaldetails where client_id='" + personid + "'";
cmd.Connection = conn;
cmd.CommandText = sqlQuery;
cmd.CommandType = System.Data.CommandType.Text;
SqlDataReader dr = null;
dr = cmd.ExecuteReader();
if (dr.Read())
{
client_id = dr["clientid"].ToString();
surname = dr["surname"].ToString();
othername = dr["othername"].ToString();
gender = dr["gender"].ToString();
date_ofbirth = (DateTime) dr["dateofbirth"];
nationality = dr["nationality"].ToString();
//age = dr["Age"];
residential_address = dr["residentialaddress"].ToString();
postal_address = dr["postaladdress"].ToString();
contact_number = dr["telephonenumber"].ToString();
marital_status = dr["maritalstatus"].ToString();
spouse_name = dr["spousename"].ToString();
email = dr["email"].ToString();
occupation = dr["occupation"].ToString();
typeof_id = dr["typeofid"].ToString();
id_number = dr["idnumber"].ToString();
id_expirydate = (DateTime) dr["idexpirydate"];
remarks = dr["remarks"].ToString();
picture = dr["picture"].ToString();
return true;
cmd.CommandText = null;
}
else
{
return false;
}
conn.Close();
}
And codes behind
private void lklSearch_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
conn.ConnectionString = "Data Source=pc101;Initial Catalog=REMITTANCE;User ID=sa;Password=mike";
conn.Open();
try
{
Personal person = new Personal();
if (person.searchpersonDetails(txtClientid.Text, txtSurname.Text))
{
var
_with3 = this;
txtClientid.Text = person.ID.ToString();
_with3.txtSurname.Text = person.Sname.ToString();
_with3.txtOthername.Text = person.Oname.ToString();
if (person.sex.ToString() == "Male")
{
optMale.Checked = true;
}
else
{
optFemale.Checked = true;
}
_with3.dtpDob.Value = person.BirthDate;
_with3.txtNationality.Text = person.country.ToString();
_with3.txtResidentialaddress.Text = person.addressResidential.ToString();
_with3.txtPostaladdress.Text = person.AddressPostal.ToString();
_with3.txtContactnumber.Text = person.NumberContact.ToString();
string mstatus = person.statusMarital.ToString();
switch (mstatus)
{
case "Single":
this.cboMaritalstatus.Text = "Single";
break;
case "Married":
_with3.cboMaritalstatus.Text = "Married";
break;
case "Widow(er)":
_with3.cboMaritalstatus.Text = "Widow(er)";
break;
case "Divorce":
_with3.cboMaritalstatus.Text = "Divorce";
break;
}
_with3.txtSpousename.Text = person.nameSpouse.ToString();
_with3.txtEmail.Text = person.mail.ToString();
_with3.txtOccupation.Text = person.Work.ToString();
string iType = person.idtype.ToString();
switch (iType)
{
case "Bank ID Card":
this.cboIdtype.Text = "Bank ID Card";
break;
case "Driver Licence":
_with3.cboIdtype.Text = "Driver Licence";
break;
case "Passport":
_with3.cboIdtype.Text = "Passport";
break;
case "National Identification":
_with3.cboIdtype.Text = "National Identification";
break;
case "NHIS":
_with3.cboIdtype.Text = "NHIS";
break;
case "SSNIT":
_with3.cboIdtype.Text = "SSNIT";
break;
case "Voters ID":
_with3.cboIdtype.Text = "Voters ID";
break;
}
_with3.txtIdnumber.Text = person.numberID.ToString();
_with3.dtpExpiringdate.Value = person.expirydateID;
_with3.txtRemarks.Text = person.myremarks.ToString();
btnPUpdate.Enabled = true;
/// this.txtChurchID.Text = this.txtID.Text;
///this.txtChurchID.ReadOnly = true;
person.searchpersonDetails(txtClientid.Text = "", txtSurname.Text = "");
}
else
{
MessageBox.Show("Record not found");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
// Close data reader object and database connection
if (conn.State == ConnectionState.Open)
conn.Close();
}
}

Is it Client_id or 'Clientid' in your database? In your query, you mentioned:
sqlQuery = "select * from tblspersonaldetails where client_id='" + personid + "'";
A few lines down, and you have:
client_id = dr["clientid"].ToString();
You should either change query to Clientid or change the code to dr[client_id] (depending on what the column name is in your database.

Related

Prevent duplicates in datagrid when databound

after some testing I came with this way to handle my datagrid. dgVariedad_CellEditEnding use the function nombreVariedadDisponible(txtBoxTemporal.Text) to check if the new value already exist in List<Variedad> variedades and it works. The problem is that the value wont be inserted in the database but will be added in the datagrid control, I can't find a way to cancel the new row in the control.
private List<Variedad> variedades = new List<Variedad>();
private void bindVariedad()
{
using (MySqlCommand cmd = Conexion.con.CreateCommand())
{
cmd.CommandText = "SELECT NOMBRE FROM DATAFRUT_VARIEDADES WHERE ELIMINADO = 'F';";
Conexion.abrirConexion();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable table = new DataTable("DATAFRUT_VARIEDADES");
da.Fill(table);
table.Columns[0].ColumnName = "Nombre";
dgVariedad.ItemsSource = table.DefaultView;
cmd.CommandText = "SELECT * FROM DATAFRUT_VARIEDADES WHERE ELIMINADO = 'F';";
using (MySqlDataReader dr = cmd.ExecuteReader())
{
variedades.Clear();
while (dr.Read())
{
Variedad var = new Variedad();
var.codigo = Convert.ToInt32(dr[0]);
var.nombre = dr[1].ToString();
var.eliminado = Convert.ToChar(dr[2]);
variedades.Add(var);
}
}
}
}
private void dgVariedad_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
TextBox txtBoxTemporal = e.EditingElement as TextBox;
int indice = e.Row.GetIndex();
if (e.Row.IsNewItem)
{
if (nombreVariedadDisponible(txtBoxTemporal.Text))
{
bool insertExitoso = false;
using (MySqlCommand cmd = Conexion.con.CreateCommand())
{
Conexion.abrirConexion();
cmd.CommandText = "INSERT INTO DATAFRUT_VARIEDADES VALUES (default, '" + txtBoxTemporal.Text + "', 'F');";
try
{
cmd.ExecuteNonQuery();
insertExitoso = true;
}
catch
{
MessageBox.Show("Error");
}
Conexion.cerrarConexion();
}
if (insertExitoso)
{
variedades.Add(Variedad.cargarUltimoInsert(txtBoxTemporal.Text));
}
}
else
{
e.Cancel = true;
}
}
else
{
using (MySqlCommand cmd = Conexion.con.CreateCommand())
{
Conexion.abrirConexion();
DataRowView dataRow = (DataRowView)dgVariedad.SelectedItem;
cmd.CommandText = "UPDATE DATAFRUT_VARIEDADES SET NOMBRE = '" + txtBoxTemporal.Text + "' WHERE CODIGO = " + variedades[dgVariedad.SelectedIndex].codigo + ";";
try
{
cmd.ExecuteNonQuery();
variedades[dgVariedad.SelectedIndex].nombre = txtBoxTemporal.Text;
}
catch(MySqlException mex)
{
MessageBox.Show("Error " + mex.Message);
}
Conexion.cerrarConexion();
}
}
}
My table on mysql has 3 fields:
int codigo (primary key, auto increment)
string Nombre (Unique) char
char Eliminado -> Eliminado (Deleted) with values (F = false and V =
true)
Here is how I check if the value already exist.
private bool nombreVariedadDisponible(string nombreAComparar)
{
//busca el nombre en la lista "variedades"
foreach (Variedad var in variedades)
{
if (var.nombre.ToLower() == nombreAComparar.ToLower() && var.eliminado == 'F')
return false;
}
return true;
}

Return string not matching textbox text

I have bit of code in my program that will not let and operator start another batch until they finish the one that they are on but still allows another operator to start the same batch. The sqldatareader is returning the correct data i.e. 17080387-002 but the program keeps going to the "Please finish batch" step. I'm trying to figure out if it possibly has anything to do with how the batch is being returned.
public void BatchLockOut()
{
string eventID = null;
string batchLock = null;
string enteredLot = TextBoxLot.Text;
string connectionString = "";
string commandText = "SELECT BadgeNo, Container_ID, Event_ID, Event_Time " +
"FROM dbo.Custom_EventLog " +
"WHERE Event_Time IN (SELECT MAX(Event_Time) FROM dbo.Custom_EventLog WHERE BadgeNo = #BADGENO)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.Parameters.Add("#BADGENO", SqlDbType.NChar, 10).Value = TextBoxLogin.Text;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
eventID = Convert.ToInt32(reader["Event_ID"]).ToString();
batchLock = reader["Container_ID"] as string;
break;
}
}
connection.Close();
}
if (batchLock == null)
{
ButtonBeginStir.IsEnabled = true;
}
else if (batchLock != enteredLot)
{
if (eventID == "1")
{
MessageBox.Show("Please finish previous stir", "Finish Stir", MessageBoxButton.OK, MessageBoxImage.Information);
ClearForm();
}
else
{
ButtonBeginStir.IsEnabled = true;
}
}
else if (batchLock == enteredLot)
{
if (eventID == "1")
{
ButtonEndStir.IsEnabled = true;
}
else if (eventID == "2")
{
ButtonBeginStir.IsEnabled = true;
}
}
}

Not sure how to 'call' the variable

I have 3 methods, called getUserID, getgazeID and updateHeatmapURL
This is getUserID
private static int getUserID()
{
int returnValue = -1;
try
{
TextReader tr = new StreamReader("C:\\Users\\L31304\\Desktop\\user.txt");
string checkedSubject = tr.ReadLine();
tr.Close();
MySqlCommand selectUser = new MySqlCommand();
selectUser.Connection = c;
selectUser.CommandText = "SELECT userID from user WHERE name= #personName";
selectUser.CommandType = CommandType.Text;
selectUser.Parameters.Add("#personName", MySqlDbType.VarChar).Value = checkedSubject;
returnValue = (int)selectUser.ExecuteScalar();
Console.WriteLine("returnValue for User-" + returnValue);
return returnValue;
}
catch (Exception e)
{
Console.WriteLine("returnValue Exception-" + e.ToString());
return returnValue;
}
}
This is getgazeID
private static int getgazeID(int userID)
{
int returnValueGaze = -1;
try
{
MySqlCommand selectGaze = new MySqlCommand();
selectGaze.Connection = c;
selectGaze.CommandText = "SELECT gazeID from gazeperiod WHERE userID = #userID";
selectGaze.CommandType = CommandType.Text;
selectGaze.Parameters.Add("#userID", MySqlDbType.Int64).Value = userID;
returnValueGaze = (int)selectGaze.ExecuteScalar();
Console.WriteLine("returnValue for Gaze-" + returnValueGaze);
return returnValueGaze;
}
catch (Exception e)
{
Console.WriteLine("returnValue Exception for gazePeriod-" + e.ToString());
return returnValueGaze;
}
}
and this is updateheatmapURL
private static int updateHeatmapURL()
{
try
{
MySqlCommand selectGaze = new MySqlCommand();
selectGaze.Connection = c;
selectGaze.CommandText = "UPDATE gazeperiod(heatmapURL) VALUES (#heatmapURL) WHERE userID = #userID AND gazeID = #gazeID";
selectGaze.CommandType = CommandType.Text;
selectGaze.Parameters.Add("#heatmapURL", MySqlDbType.VarChar).Value = dlg.FileName;
selectGaze.Parameters.Add("#userID", MySqlDbType.Int64).Value = userID;
selectGaze.Parameters.Add("#gazeID", MySqlDbType.Int64).Value = gazeID;
selectGaze.ExecuteScalar();
Console.WriteLine("heatmapURL - " + dlg.FileName);
}
catch (Exception e)
{
Console.WriteLine("Exception for heatmapURL-" + e.ToString());
}
}
And this is where dlg comes from.
public static bool ExportImageToFile(Image image)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Title = "Please enter filename for image...";
dlg.InitialDirectory = Environment.SpecialFolder.MyDocuments.ToString();
dlg.Filter = "JPEG Format - jpg|*.jpg|Bitmap Format - bmp|*.bmp|Graphics Interchange Format - gif|*.gif|Portable Networks Graphic - png|*.png|Tag Image File Format - tif|*.tif|Windows MetaFile Format - wmf|*.wmf";
dlg.FileName = "*.jpg";
dlg.AddExtension = true;}
However, the userID, gazeID and dlg.FileName says:
'the name does not exist in the current context.'
How do I call it in updateURL so that it exists?
public static bool ExportImageToFile(Image image)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Title = "Please enter filename for image...";
dlg.InitialDirectory = Environment.SpecialFolder.MyDocuments.ToString();
//dlg.InitialDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "new_folder2");
bool saveToServer = false;
//check....
if (System.IO.File.Exists("C:\\Users\\L31304\\Desktop\\user.txt"))
{
dlg.InitialDirectory = #"\\111.11.111.111\c$\Users\L31303\person\EyeTrackerWeb\WebContent\uploadheatmap";
saveToServer = true;
}
//set bool to true
//end if
dlg.Filter = "JPEG Format - jpg|*.jpg|Bitmap Format - bmp|*.bmp|Graphics Interchange Format - gif|*.gif|Portable Networks Graphic - png|*.png|Tag Image File Format - tif|*.tif|Windows MetaFile Format - wmf|*.wmf";
dlg.FileName = "*.jpg";
dlg.AddExtension = true;
dlg.RestoreDirectory = true;
if (dlg.ShowDialog() == DialogResult.OK)
{
ImageFormat format;
switch (dlg.FilterIndex)
{
case 1:
format = ImageFormat.Jpeg;
break;
case 2:
format = ImageFormat.Bmp;
break;
case 3:
format = ImageFormat.Gif;
break;
case 4:
format = ImageFormat.Png;
break;
case 5:
format = ImageFormat.Tiff;
break;
case 6:
format = ImageFormat.Wmf;
break;
default:
format = ImageFormat.Jpeg;
break;
}
try
{
image.Save(dlg.FileName, format);
Console.WriteLine("file name is" + dlg.FileName);
if (saveToServer == true)
{
connectDB();
OpenConnection();
int userID = getUserID();
int gazeID = getgazeID(userID);
CloseConnection();
}
else
{
}
//if bool == true, then do the following
//select userID from user table WHERE name is name from text file
//select gazePeriodID from gazePeriod where userID the above selected userID
//update image path to gazePeriod in heatmapimage
//delete text file
}
catch (Exception ex)
{
VGExceptionMethods.HandleException(ex);
return false;
}
}
return true;
}
private static int getUserID()
{
int returnValue = -1;
try
{
TextReader tr = new StreamReader("C:\\Users\\L31304\\Desktop\\user.txt");
string checkedSubject = tr.ReadLine();
tr.Close();
MySqlCommand selectUser = new MySqlCommand();
selectUser.Connection = c;
selectUser.CommandText = "SELECT userID from user WHERE name= #personName";
selectUser.CommandType = CommandType.Text;
selectUser.Parameters.Add("#personName", MySqlDbType.VarChar).Value = checkedSubject;
returnValue = (int)selectUser.ExecuteScalar();
Console.WriteLine("returnValue for User-" + returnValue);
return returnValue;
}
catch (Exception e)
{
Console.WriteLine("returnValue Exception-" + e.ToString());
return returnValue;
}
}
private static int getgazeID(int userID)
{
int returnValueGaze = -1;
try
{
MySqlCommand selectGaze = new MySqlCommand();
selectGaze.Connection = c;
selectGaze.CommandText = "SELECT gazeID from gazeperiod WHERE userID = #userID";
selectGaze.CommandType = CommandType.Text;
selectGaze.Parameters.Add("#userID", MySqlDbType.Int64).Value = userID;
returnValueGaze = (int)selectGaze.ExecuteScalar();
Console.WriteLine("returnValue for Gaze-" + returnValueGaze);
return returnValueGaze;
}
catch (Exception e)
{
Console.WriteLine("returnValue Exception for gazePeriod-" + e.ToString());
return returnValueGaze;
}
}
public class Form1 : Form
{
private static Form1 _instance;
public Form1()
{
this.InitializeComponent();
_instance = this;
}
private static int updateHeatmapURL()
{
try
{
MySqlCommand selectGaze = new MySqlCommand();
selectGaze.Connection = c;
selectGaze.CommandText = "UPDATE gazeperiod(heatmapURL) VALUES (#heatmapURL) WHERE userID = #userID AND gazeID = #gazeID";
selectGaze.CommandType = CommandType.Text;
var userID = getUserID();
selectGaze.Parameters.Add("#heatmapURL", MySqlDbType.VarChar).Value = _instance.dlg.FileName;
selectGaze.Parameters.Add("#userID", MySqlDbType.Int64).Value = userID;
selectGaze.Parameters.Add("#gazeID", MySqlDbType.Int64).Value = getgazeID(userID);
selectGaze.ExecuteScalar();
Console.WriteLine("heatmapURL - " + _instance.dlg.FileName);
}
catch (Exception e)
{
Console.WriteLine("Exception for heatmapURL-" + e.ToString());
}
}
}
The class is
public class Images
{
private static MySqlConnection c;
private static string server;
private static string database;
private static string uid;
private static string password;
Try this
//update these lines in updateHeatmapURL mthod
// dlg.File name is not accessable because updateHeatmapURL method is static
// use instance to access dlg or remove static, if you remove static then you need to remove it from other two methods as well
var userId = getUserID();
selectGaze.Parameters.Add("#userID", MySqlDbType.Int64).Value = userId;
selectGaze.Parameters.Add("#gazeID", MySqlDbType.Int64).Value = getgazeID(userId);
EDIT
public class Form1 : Form
{
private static Form1 _instance;
public Form1()
{
InitializeComponent();
_instance = this;
}
private static int updateHeatmapURL()
{
...
selectGaze.Parameters.Add("#heatmapURL", MySqlDbType.VarChar).Value = _instance.dlg.FileName;
var userId = getUserID();
selectGaze.Parameters.Add("#userID", MySqlDbType.Int64).Value = userId;
selectGaze.Parameters.Add("#gazeID", MySqlDbType.Int64).Value = getgazeID(userId);
...
}
}

Slow data Selection from MDB file to C# Desktop application

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();
}
}}

How to store results returned from SqlDataReader?

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();
}
}
}

Categories

Resources