Calculating columns in a listview - c#

I am new to programming and I have a price list in a list view, I would like to have another column that calculates the last column and a textbox together, please point me in the right direction as I am getting method and format errors.. here is my code:
listView1.Items.Clear();
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:xxxx;Persist Security Info=False");
OleDbCommand command = connection.CreateCommand();
if (comboBox1.Text == "Brickcom")
{
ListViewItem li;
command.CommandText = "SELECT [PartNo], [Category], [Product], [Resolution], [IncludedAccessories], [Price] FROM [Brickcom] WHERE ([Manufacturer] Like '" + comboBox1.Text.ToString() + "')";
connection.Open();
OleDbDataReader reader = command.ExecuteReader(CommandBehavior.Default);
while (reader.Read())
{
listView1.Columns[0].Text = null;
listView1.Columns[1].Text = null;
listView1.Columns[2].Text = null;
listView1.Columns[3].Text = null;
listView1.Columns[4].Text = null;
listView1.Columns[5].Text = null;
listView1.Columns[6].Text = null;
listView1.Columns[7].Text = null;
listView1.Columns[8].Text = null;
listView1.Columns[0].Text = "Part Number";
listView1.Columns[1].Text = "Category";
listView1.Columns[2].Text = "Product";
listView1.Columns[3].Text = "Resolution";
listView1.Columns[4].Text = "Included Accessories";
listView1.Columns[5].Text = "Price";
li = listView1.Items.Add(reader[0].ToString());
li.SubItems.Add(reader[1].ToString());
li.SubItems.Add(reader[2].ToString());
li.SubItems.Add(reader[3].ToString());
li.SubItems.Add(reader[4].ToString());
li.SubItems.Add(reader[5].ToString());
foreach (ListViewItem item in listView1.Items)
{
li.SubItems.Add(items[6].ToString());
//listView1.Columns[6].Text = (Int32.Parse(textBox1.Text) * Int32.Parse(textBox2.Text)).ToString();
item.SubItems[6].Text = (Int32.Parse(textBox1.Text) * Int32.Parse(textBox2.Text)).ToString();
}
}
connection.Close();
}

Related

need a quicker way to select data and paste it in an excel sheet

It took me a while to just find a way to select data from my database and then paste it in an excel spreadsheet. Now that I've found it, it runs dirt slow. Like I said before, I've looked at a lot of different ways to accomplish this but have not been able to correctly implement any of them except for this. I'm not married to this option but it is the only one I could get to work. Could someone help me out by suggesting a quicker way to accomplish this simple task? Please see my code below.
Record850 rec850 = new Record850();
List<Record850> lst850records = new List<Record850>();
//SqlConnection connStr = new SqlConnection("Server = 172.18.211.76; Database = Processstage; User Id = brendon.davies; Password = mypassword;");
SqlConnection conn = new SqlConnection("Server = 172.18.211.76; Database = Processstage; User Id = brendon.davies; Password = mypassword;");
//SqlConnection sqlConnection1 = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = Select_850;
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
conn.Open();
Record850 reco850 = new Record850();
string strComplete = "";
reader = cmd.ExecuteReader();
while (reader.Read())
{
try
{
reco850.OrgName = reader.GetString(0);
reco850.WholeSalerAccountDivisionCode = reader.GetString(1);
reco850.File_Process_Name = reader.GetString(2);
reco850.Pur_Ord_Num_BEG03 = reader.GetString(3);
reco850.File_Process_ID = reader.GetInt64(4);
reco850.CECode = reader.GetString(5);
reco850.CEName = reader.GetString(6);
reco850.Modified_Date = reader.GetDateTime(7);
lst850records.Add(reco850);
reco850 = new Record850();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
conn.Close();
eWorkSheet = (Excel.Worksheet)oSheets.get_Item("850_Template");
eWorkSheet.Activate();
int int850counter = 0;
int int850RowCounter = 3;
foreach (Record850 r850 in lst850records)
{
strComplete = lst850records[int850counter].OrgName + "\t" +
lst850records[int850counter].WholeSalerAccountDivisionCode + "\t" +
lst850records[int850counter].File_Process_Name + "\t" +
lst850records[int850counter].Pur_Ord_Num_BEG03 + "\t" +
lst850records[int850counter].File_Process_ID + "\t" +
lst850records[int850counter].CECode + "\t" +
lst850records[int850counter].CEName+ "\t" +
lst850records[int850counter].Modified_Date;
CR = (Excel.Range)eWorkSheet.Cells[int850RowCounter,3];
Clipboard.SetText(strComplete);
CR.Select();
eWorkSheet.Paste(CR, false);
Clipboard.Clear();
int850RowCounter++;
int850counter++;
strComplete = ""
}
Here's an answer that also runs quickly, just about the same as the use of EPPlus above. Do not attempt the cell by cell approach (commented out below) as that indeed runs at a snail's pace by comparison.
[STAThread]
static void Main(string[] args)
{
Excel.Application xl = null;
try {
xl = new Excel.Application();
xl.ScreenUpdating = false;
xl.Visible = false;
xl.UserControl = false;
var wb = xl.Workbooks.Open(SOURCE_PATH);
var ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Sheets.Item["850_Template"];
StringBuilder sb = new StringBuilder();
//int row = 3;
// var a1 = ws.Range["A1", Missing.Value];
using (SqlConnection cn = new SqlConnection(CN_STR)) {
cn.Open();
using (SqlCommand cmd = new SqlCommand(SQL, cn)) {
cmd.CommandType = CommandType.Text;
using (SqlDataReader dr = cmd.ExecuteReader()) {
while (dr.Read())
{
sb.AppendFormat("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\r\n",
(string)dr["OrgName"],
(string)dr["WholeSalerAccountDivisionCode"],
(string)dr["File_Process_Name"],
(string)dr["Pur_Ord_Num_BEG03"],
(long)dr["File_Process_ID"],
(string)dr["CECode"],
(string)dr["CEName"],
(DateTime)dr["Modified_Date"]
);
//a1.Offset[row, 0].Value = (string)dr["OrgName"];
//a1.Offset[row, 1].Value = (string)dr["WholeSalerAccountDivisionCode"];
//a1.Offset[row, 2].Value = (string)dr["File_Process_Name"];
//a1.Offset[row, 3].Value = (string)dr["Pur_Ord_Num_BEG03"];
//a1.Offset[row, 4].Value = (long)dr["File_Process_ID"];
//a1.Offset[row, 5].Value = (string)dr["CECode"];
//a1.Offset[row, 6].Value = (string)dr["CEName"];
//a1.Offset[row, 7].Value = (DateTime)dr["Modified_Date"];
//row++;
}
}
}
cn.Close();
}
Clipboard.SetText(sb.ToString(),
TextDataFormat.Text);
var rng = ws.Range["A3", Missing.Value];
rng.Select();
ws.Paste(rng, Missing.Value);
Clipboard.Clear();
wb.Save();
wb.Close();
xl.Quit();
} catch (Exception ex) {
Console.WriteLine(ex.Message);
if (xl != null) {
xl.ScreenUpdating = true;
xl.Visible = true;
xl.UserControl = true;
}
}
}
Here's an alternative that uses the EPPlus approach, much faster.
try {
var app = new ExcelPackage(new FileInfo(SOURCE_PATH));
var ws = app.Workbook.Worksheets["850_Template"];
int row = 3;
using (SqlConnection cn = new SqlConnection(CN_STR)) {
cn.Open();
using (SqlCommand cmd = new SqlCommand(SQL, cn)) {
cmd.CommandType = CommandType.Text;
using (SqlDataReader dr = cmd.ExecuteReader()) {
while (dr.Read())
{
ws.SetValue(row, 1, (string) dr["OrgName"]);
ws.SetValue(row, 2, (string) dr["WholeSalerAccountDivisionCode"]);
ws.SetValue(row, 3, (string) dr["File_Process_Name"]);
ws.SetValue(row, 4, (string) dr["Pur_Ord_Num_BEG03"]);
ws.SetValue(row, 5, (long) dr["File_Process_ID"]);
ws.SetValue(row, 6, (string) dr["CECode"]);
ws.SetValue(row, 7, (string) dr["CEName"]);
ws.SetValue(row, 8, (DateTime) dr["Modified_Date"]);
row++;
}
}
}
cn.Close();
}
app.Save();
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}

Updating DATAGRID row to save to SQL

Hi Guys I am trying to understand how to save and edited row to the database
private void BudgetGrid_RowEditEnding(object sender,
DataGridRowEditEndingEventArgs e)
{
SqlCommand gridcmd = new SqlCommand();
SqlConnection rwConn = null;
rwConn = new SqlConnection("server=localhost;" +
"Trusted_Connection=yes;" + "database=Production; " + "connection
timeout=30");
gridcmd.Connection = rwConn;
rwConn.Open();
//gridcmd.CommandText =
//"SELECT Id, Name, Quantity, Rate, Time FROM Budget";
gridcmd.CommandText =
"UPDATE Budget SET Id = #id, Name = #Name, " +
"Quantity = #Qty, Rate = #Rte WHERE Time = #Time";
SqlDataAdapter gridda = new SqlDataAdapter(gridcmd);
string strId = "#id".ToString();
int intID;
bool bintID = Int32.TryParse(strId, out intID);
string strName = "#Name".ToString();
string strQty = "#Qty".ToString();
int intQty;
bool bintQty = Int32.TryParse(strQty, out intQty);
string strRte = "#Rte".ToString();
int intRte;
bool bintRte = Int32.TryParse(strRte, out intRte);
string strTime = "#Time".ToString();
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#id", SqlDbType.Int));
gridda.SelectCommand.Parameters["#id"].SqlValue = intID;
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#Name", SqlDbType.VarChar));
gridda.SelectCommand.Parameters["#Name"].SqlValue = strName;
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#Qty", SqlDbType.Int));
gridda.SelectCommand.Parameters["#Qty"].SqlValue = strQty;
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#Rte", SqlDbType.Int));
gridda.SelectCommand.Parameters["#Rte"].SqlValue = strRte;
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#Time", SqlDbType.VarChar));
gridda.SelectCommand.Parameters["#Time"].SqlValue = strTime;
DataTable griddt = new DataTable("Budget");
gridda.Fill(griddt);
gridda.UpdateCommand =
new SqlCommandBuilder(gridda).GetUpdateCommand();
BudgetGrid.ItemsSource = griddt.DefaultView;
gridda.Update(griddt);
rwConn.Close();
}
it displays fine. I can edit its but when I click on the other tab it does not update it goes back to the original data.
Most of the code I have been going through its either out dated.. or not what I am looking for.
so here is the database
and here is the app
so basically if i hit tab to the next row. under the event BudgetGrid_RowEditEnding it should update the database.. but now its not.
Just copy below codes. I've created all the thing of you and tested successfully. Rather than the first way, I tried to let you go more popular way. Therefore, it took me time to adopt..
Hope this helps you !
SqlDataAdapter da;
DataTable dt;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
SqlConnection Conn = new SqlConnection();
Conn.ConnectionString = yourConnectionString;
Conn.Open();
SqlCommand gridcomm = new SqlCommand();
gridcomm.Connection = Conn;
gridcomm.CommandText = "SELECT Id, Name, Quantity, Rate, Time FROM Budget";
da = new SqlDataAdapter(gridcomm);
SqlDataReader gridreader = gridcomm.ExecuteReader();
while (gridreader.Read())
{
}
gridreader.Close();
dt= new DataTable("Budget");
da.Fill(dt);
dataGrid_Budget.ItemsSource = dt.DefaultView;
Conn.Close();
}
private void dataGrid_Budget_RowEditEnding(object sender, System.Windows.Controls.DataGridRowEditEndingEventArgs e)
{
DataGridRow editedrow = e.Row;
int row_index = (DataGrid)sender).ItemContainerGenerator.IndexFromContainer(editedrow);
for (int k=0;k< 5;k++)
{
DataGridCell cell = GetCell(row_index, k);
TextBlock tb = cell.Content as TextBlock;
if (k==1)
{
dt.Rows[row_index][k] = tb.Text;
}
else if (k == 4)
{
if (tb.Text != "")
{
dt.Rows[row_index][k] = Convert.ToDateTime(tb.Text);
}
}
else
{
dt.Rows[row_index][k] = Convert.ToInt32(tb.Text);
}
}
da.UpdateCommand = new SqlCommandBuilder(da).GetUpdateCommand();
da.Update(dt);
}
public DataGridCell GetCell(int row, int column)
{
DataGridRow rowContainer = GetRow(row);
if (rowContainer != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
if (cell == null)
{
dataGrid_Budget.ScrollIntoView(rowContainer, dataGrid_Budget.Columns[column]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
}
return cell;
}
return null;
}
public DataGridRow GetRow(int index)
{
DataGridRow row = (DataGridRow)dataGrid_Budget.ItemContainerGenerator.ContainerFromIndex(index);
if (row == null)
{
dataGrid_Budget.UpdateLayout();
dataGrid_Budget.ScrollIntoView(dataGrid_Budget.Items[index]);
row = (DataGridRow)dataGrid_Budget.ItemContainerGenerator.ContainerFromIndex(index);
}
return row;
}
public static T GetVisualChild<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}
Your SQL syntax has to be corrected like,
SqlCommand update_comm = new SqlCommand();
update_comm.Connection = Conn;
update_comm.CommandText = "UPDATE Budget SET id= #u_id, Name= #u_name WHERE person= #psn";
var update_da = new SqlDataAdapter(update_comm);
update_da.SelectCommand.Parameters.Add(new SqlParameter("#u_id", SqlDbType.Int));
update_da.SelectCommand.Parameters["#u_id"].Value = yourintvalue;
update_da.SelectCommand.Parameters.Add(new SqlParameter("#u_name", SqlDbType.NVarChar));
update_da.SelectCommand.Parameters["#u_name"].Value = yourstringvalue;
update_da.SelectCommand.Parameters.Add(new SqlParameter("#psn", SqlDbType.NVarChar));
update_da.SelectCommand.Parameters["#psn"].Value = yourstringvalue;
var update_ds = new DataSet();
update_da.Fill(update_ds);
'UPDATE' should be used with 'SET' together.
And if you want to update the actual SQL database with the value of edited rows of DataGrid, please try this.
da.UpdateCommand = new SqlCommandBuilder(da).GetUpdateCommand();
da.Update(griddt);
SqlConnection uniConn = null;
SqlCommand cmd = null;
SqlDataAdapter sda = null;
DataTable dt = new DataTable();
uniConn = new SqlConnection(
"server=localhost;" + "Trusted_Connection=yes;" +
"database=Production; " + "connection timeout=30");
cmd = new SqlCommand("UPDATE Budget(id, Name, Quantity, Rate, Time)",
uniConn);
uniConn.Open();
sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
BudgetGrid.ItemsSource = dt.DefaultView;
uniConn.Close();
Did you forget to close the connection?

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

Convert Rank to percentage C#

I am trying to display percentage based on the rank of each record returned in search. I want it to loop through each item but it only loops through the first item as many times as I have items. For instance if it found 4 results it would display the rank of the first one on all 4 results.
Any suggestions to get it to display each rank separately and convert it to percentage?
private void BindRpt()
{
if (string.IsNullOrEmpty(txtSearch.Text)) return;
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString);
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.CommandText = "select Distinct Rank, SUBSTRING(ColumnA, 1, 500) AS ColumnA, ColumnB, ColumnC, ColumnD, ColumnE from FREETEXTTABLE (TABLE , ColumnA, '" + Search.Text + "' ) S, TABLE C WHERE c.ID = S.[KEY] order by Rank Desc";
DataTable dt = new DataTable();
adapter.SelectCommand = cmd;
adapter.Fill(dt);
PagedDataSource pgitems = new PagedDataSource();
pgitems.DataSource = dt.DefaultView;
pgitems.AllowPaging = true;
pgitems.PageSize = 3;
pgitems.CurrentPageIndex = PageNumber;
if (pgitems.Count > 1)
{
rptPaging.Visible = true;
ArrayList pages = new ArrayList();
for (int i = 0; i <= pgitems.PageCount - 1; i++)
{
pages.Add((i + 1).ToString());
}
rptPaging.DataSource = pages;
rptPaging.DataBind();
lblSentence.Visible = true;
lblSearchWord.Visible = true;
lblSearchWord.Text = txtSearch.Text;
}
else
{
rptPaging.Visible = false;
lblSentence.Visible = true;
lblSentence.Text = "Results were found for";
lblSearchWord.Visible = true;
lblSearchWord.Text = txtSearch.Text;
}
rptResults.DataSource = pgitems;
rptResults.DataBind();
cn.Close();
}
protected void rptResults_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["HTAA"].ConnectionString);
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.CommandText = "select Distinct Rank, SUBSTRING(ColumnA, 1, 500) AS ColumnA, ColumnB, ColumnC, ColumnD, ColumnE from FREETEXTTABLE (TABLE , ColumnA, '" + Search.Text + "' ) S, TABLE C WHERE c.ID = S.[KEY] order by Rank Desc";
int number = Page.Items.Count;
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
int firstrank = dr.GetInt32(0);
while (dr.Read())
{
int rank = dr.GetInt32(0);
int percentage = (rank / firstrank) * 100;
Label lblpre = (Label)e.Item.FindControl("lblRank");
lblpre.Text = percentage.ToString();
}
}
dr.Close();
cn.Close();
}
After a chat, I have a better handle on things. A way to do this;
Create a private field on your code behind file.
private int topRanked = 0;
In your Bind method()
private void Bind()
{
...
DataTable dt = new DataTable();
adapter.SelectCommand = cmd;
adapter.Fill(dt);
topRanked = (int)dt.Rows[0]["Rank"];
Now, make your OnItemDataBound method;
protected void OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
var dataItem = e.Item.DataItem as DataRowView;
int rank = (int) dataItem["Rank"];
var percentage = ((double)topRanked / rank) * 100;
Label label = (Label)e.Item.FindControl("labelRank");
label.Text = percentage.ToString();
}
as mentioned. I don't believe it's the best answer, but it is an answer. I'm sure a stored procedure, or even a better sql method could probably calculate this and not leave you making calculations in code.
Can you try with while(dr.Read()) instead of "if"?
You will want to loop over the result set
while (dr.Read())
{
int rank = dr.GetInt32(0);
int percentage = (rank / rank) * 100;
Label lblpre = (Label)e.Item.FindControl("lblRank");
lblpre.Text = rank.ToString();
}
"but it only loops through the first item" - because you have a for and checks for i <= 0
for (int i = 0; i <= 0; i++)
{
....
}
You just don't need this for statement but rather use
if (dr != null)
using (dr)
{
while (dr.Read())
{
..
}
}
It's always better to use using when dealing with db connection objects so the resources used by these objects are properly disposed after it's been used.

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