Displaying the Incorrect Cost - c#

My goal is to display the cost for a One-Day Conference on a web page, which is $50.00. However, I keep getting $0.00 in return. I tested my SELECT statement in SQL and it is retrieving the correct data. Now I have narrowed down the problem to be in my if...else if statements in the PayBackCC method but I am not certain. It should get the cost from variable cOneDCost. Any help is appreciated.
Code behind
protected void PayBackInfo()
{
try
{
con.Open();
SqlCommand PBCredit = new SqlCommand("SELECT * FROM PaymentInfo, ConferenceReg WHERE PaymentInfoID=PaymentInfoIDNum AND PaymentInfoID=#payID AND ConferenceReg.Deleted='N' AND ConferenceIDNum=#confID", con);
PBCredit.Parameters.AddWithValue("#confID", confID);
PBCredit.Parameters.AddWithValue("#payID", Request.QueryString["payID"]);
SqlDataReader readerPB = PBCredit.ExecuteReader();
while (readerPB.Read())
{
piID = readerPB["PaymentInfoID"].ToString();
cID = readerPB["ConferenceIDNum"].ToString();
poID = readerPB["PurchaseOrder"].ToString();
partnersNum = readerPB["PartnersIDNum"].ToString();
cFullCost = Convert.ToDecimal(readerPB["ConferenceFullFee"]).ToString("#,##0.00");
cOneDCost = Convert.ToDecimal(readerPB["ConferenceOneDayFee"]).ToString("#,##0.00");
partnersCost = Convert.ToDecimal(readerPB["PartnersFee"]).ToString("#,##0.00");
PayBackCC();
}
readerPB.Close();
}
finally
{
con.Close();
}
}
private void PayBackCC()
{
if (!partnersNum.Equals("null") || !partnersNum.Equals("0"))
{
msgLbl.Text = "$" + partnersCost;
}
else if (!cFullCost.Equals("0"))
{
msgLbl.Text = "$" + cFullCost;
}
else if (!cOneDCost.Equals("0"))
{
msgLbl.Text = "$" + cOneDCost;
}
}

Please change
if (!partnersNum.Equals("null") || !partnersNum.Equals("0"))
to
if (!String.IsNullOrEmpty(partnersNum) || !partnersNum.Equals("0"))
unless you are expecting "null" string from your query

Related

My boolean value is false even though all the code is correct

About my Program:
My algorithm(this class) is meant to check whether a delivery has been finished and afterwards makes the truck/trailer/driver available for another delivery, at the same time this algorithm sends another truck/trailer/driver on a delivery. To sum it up this class does the following:
Check whether a booking is in Allocation mode (Allocation mode basically means that the "booking" is in progress of being delivered
Check whether there is tonnage left of the booking (Ex. I want to sent 500 ton to a place, but a delivery can only be 30 ton at a time so it checks if there is still ton that needs to be delivered)
To make the Driver(s)/Truck(s)/Trailer(s) available that finished their delivery.
To automatically allocate tonnage to a Driver/Trailer/Truck.
Deleting entries that are finished (any bookings that are finished - Logs still stay in the database).
My Problem:
I have no idea what is wrong with my class, I have been hours at it and can't seem to figure out what is causing my boolean variable (forLoopBreak) to trigger a "false" value when it is calling the method checkAvailTrailers(). The problem seems to be in there but I can't figure out what causes the problem.
Class:
[https://pastebin.com/4up8eppd][1]
( I couldn't paste it here as I met the limit of characters)
Notes:
I know my programming looks but, but I am still new to this.
I decided to attach the whole class as the problem may be at a different place.
Edit:
My code is too large to investigate so here is the relevant parts:
private void startAlgo()
{
checkAvailTrailers();
if (forloopBreak == false)
{
setErrorMessage("Avail Trailers not enough!");
}
}
private void checkAvailTrailers()
{
string trailerRouteAllocation = null;
string trailerVragAllocation = null;
string tempHolderTrailer = null;
string myNewTempT = null;
string trailermyTemp = null;
int trailerCount = 0;
int tempTra = -1;
//Gets trailer route classification
using (SqlCommand selectTrailer = new SqlCommand("SELECT [TR_Routes] FROM dbo.TrailerDetail WHERE [TR_Allocation] = " + 0, con))
{
using (SqlDataReader reader = selectTrailer.ExecuteReader())
{
while (reader.Read())
{
trailerRouteAllocation = reader.GetString(0);
tempHolderTrailer = trailerRouteAllocation;
myNewTempT = trailerRouteAllocation;
for (int l = 0; l < tempHolderTrailer.Length; l++)
{
tempTra = myNewTempT.IndexOf(",");
if (tempTra >= 0)
{
trailermyTemp = myNewTempT.Substring(0,tempTra);
}
else
{
trailermyTemp = myNewTempT;
if (trailermyTemp == myCurrentBookingRoute.ToString())
{
mycurrentTrailerAvailableRoute[trailerCount] = tempHolderTrailer;
}
break;
}
myNewTempT = myNewTempT.Substring(tempTra + 1);
if (trailermyTemp == myCurrentBookingRoute.ToString())
{
mycurrentTrailerAvailableRoute[trailerCount] = trailerRouteAllocation;
}
}
trailerCount++;
}
reader.Close();
}
}
//gets trailer vrag classification.
int countTrailerVrag = 0;
for (int l = 0; l < mycurrentTrailerAvailableRoute.Length; l++)
{
if (mycurrentTrailerAvailableRoute[l] != null)
{
using (SqlCommand select = new SqlCommand("Select [TR_Classification] FROM dbo.TrailerDetail WHERE [TR_Routes] = '" + mycurrentTrailerAvailableRoute[l] + "' AND [TR_Allocation] = " + 0, con))
{
using (SqlDataReader readerS = select.ExecuteReader())
{
while (readerS.Read())
{
trailerVragAllocation = readerS.GetString(0);
myAvailableTrailerVragClassification[countTrailerVrag] = trailerVragAllocation;
countTrailerVrag++;
}
readerS.Close();
}
}
}
}
int countTrailers = 0;
string trailerRegNum = null;
for (int l = 0; l < mycurrentTrailerAvailableRoute.Length; l++)
{
if (mycurrentTrailerAvailableRoute[l] != null)
{
using (SqlCommand selectT = new SqlCommand("Select [TR_RegNumber] FROM dbo.TrailerDetail WHERE [TR_Routes] = '" + mycurrentTrailerAvailableRoute[l] + "'" + " AND [TR_Classification] = '" + myAvailableTrailerVragClassification[l] + "' AND [TR_Allocation] = " + 0, con))
{
SqlDataReader readerT = selectT.ExecuteReader();
if (readerT.HasRows)
{
while (readerT.Read())
{
trailerRegNum = readerT.GetString(0);
myAvailableCurrentTraillerRegNumber[countTrailers] = trailerRegNum;
countTrailers++;
}
}
else
{
forloopBreak = false;
}
readerT.Close();
}
}
}//END OF TRAILER CHECKING
//gets trailer's max tonnage
int myTrailerTonMax = 0;
int myTrailerTon = 0;
for (int l = 0; l < mycurrentTrailerAvailableRoute.Length; l++)
{
if (mycurrentTrailerAvailableRoute[l] != null)
{
using (SqlCommand selectT = new SqlCommand("Select [TR_MaxTonnage] FROM dbo.TrailerDetail WHERE [TR_Routes] = '" + mycurrentTrailerAvailableRoute[l] + "'" + " AND [TR_Classification] = '" + myAvailableTrailerVragClassification[l] + "'", con))
{
using (SqlDataReader readerS = selectT.ExecuteReader())
{
while (readerS.Read())
{
myTrailerTon = readerS.GetInt32(0);
myTrailerAvailableTonMax[myTrailerTonMax] = myTrailerTon;
myTrailerTonMax++;
}
readerS.Close();
}
}
}
}
}
Extra:
- The data in my database matches the criteria, the while loop even executes but in the end my boolean value returns a false.
The readerT.HasRows clause will always be true if there is any data initially in the reader. Here is the property's description from the MSDN page
Gets a value that indicates whether the SqlDataReader contains one or more rows.
What you want to do instead (I assume) is set forloopBreak = false; when the while loop is finished. So inside the using block you put this:
SqlDataReader readerT = selectT.ExecuteReader();
while (readerT.Read())
{
trailerRegNum = readerT.GetString(0);
myAvailableCurrentTraillerRegNumber[countTrailers] = trailerRegNum;
countTrailers++;
}
forloopBreak = false;
readerT.Close();
Let me know if this works!

Getting passbok view total in grid using c#

I am using Data Grid to show passbook balance. I have done everything I'm unable to get the balance value in the respective column.
private void dgview2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
int credit1, debit1;
int balance = new int();
if (int.TryParse(dgview2.Rows[e.RowIndex].Cells["debit"].Value.ToString(),
out debit1) && int.TryParse(dgview2.Rows[e.RowIndex].Cells["credit"].Value.ToString(),
out credit1) && int.TryParse(dgview2.Rows[e.RowIndex].Cells["balance"].Value.ToString(),
out balance))
{
balance = balance + credit1 - debit1;
dgview2.Rows[e.RowIndex].Cells["balance"].Value = balance.ToString();
}
}
Vfp9sp2 Application output
here is the code which i am useing to populate grid
private void fill_div()
{
var com = new MySqlCommand("Select *From shtrn where mem_no ='" + textBox1.Text + "' order by tdate ", con_db.con);
var dr = com.ExecuteReader();
try
{
dgview2.Rows.Clear();
while (dr.Read())
{
var n = dgview2.Rows.Add();
dgview2.Rows[n].Cells[0].Value = Convert.ToDateTime(dr["tdate"].ToString());
dgview2.Rows[n].Cells[1].Value = dr["particular"].ToString();
dgview2.Rows[n].Cells[2].Value = dr["trmode"].ToString();
dgview2.Rows[n].Cells[3].Value = dr["debit"].ToString();
dgview2.Rows[n].Cells[4].Value = dr["credit"].ToString();
dgview2.Rows[n].Cells[5].Value = dr["balance"].ToString();
dgview2.FirstDisplayedScrollingRowIndex = n;
dgview2.CurrentCell = dgview2.Rows[n].Cells[0];
UpdateBalance();
}
{
dr.Close();
}
}
catch (FormatException)
{
MessageBox.Show("No Records Found ");
}
}
The reason code does not work is that grid is made read only, therefore code specified in the event handler (dgview2_CellEndEdit) is not triggered.
Ideally you should be making balance calculations before updating the grid, but as a quick workaround you can move the code to a private method like this:
private void UpdateBalance()
{
for (int i = 0; i < dgview2.Rows.Count; i++)
{
int credit1, debit1, balance;
if (int.TryParse(dgview2.Rows[i].Cells[3].Value.ToString(),
out debit1) && int.TryParse(dgview2.Rows[i].Cells[4].Value.ToString(),
out credit1) && int.TryParse(dgview2.Rows[i].Cells[5].Value.ToString(),
out balance))
{
balance = balance + credit1 - debit1;
dgview2.Rows[i].Cells[5].Value = balance.ToString();
}
}
}
Then call this method after you finished populating the grid:
UpdateBalance();
The method iterates over each row and updates balance cells using the same logic.
[Edit for update code]
Instead of above, you can perform calculation in your update logic as below:
while (dr.Read())
{
var n = dgview2.Rows.Add();
dgview2.Rows[n].Cells[0].Value = Convert.ToDateTime(dr["tdate"].ToString());
dgview2.Rows[n].Cells[1].Value = dr["particular"].ToString();
dgview2.Rows[n].Cells[2].Value = dr["trmode"].ToString();
dgview2.Rows[n].Cells[3].Value = dr["debit"].ToString();
dgview2.Rows[n].Cells[4].Value = dr["credit"].ToString();
dgview2.Rows[n].Cells[5].Value = dr["balance"].ToString();
int credit1, debit1, balance;
if (int.TryParse(dr["debit"].ToString(),
out debit1) && int.TryParse(dr["credit"].ToString(),
out credit1) && int.TryParse(dr["balance"].ToString(),
out balance))
{
dgview2.Rows[n].Cells[5].Value = balance + credit1 - debit1;
}
dgview2.FirstDisplayedScrollingRowIndex = n;
dgview2.CurrentCell = dgview2.Rows[n].Cells[0];
}

Should I refactor this, or is my confusion cause to be cautious? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
This SqlCe code looks awfully strange to me:
cmd.CommandText = "INSERT INTO departments ( account_id, name) VALUES (?, ?)";
foreach(DataTable tab in dset.Tables)
{
if (tab.TableName == "Departments")
{
foreach(DataRow row in tab.Rows)
{
Department Dept = new Department();
if (!ret)
ret = true;
foreach(DataColumn column in tab.Columns)
{
if (column.ColumnName == "AccountID")
{
Dept.AccountID = (string) row[column];
}
else if (column.ColumnName == "Name")
{
if (!row.IsNull(column))
Dept.AccountName = (string) row[column];
else
Dept.AccountName = "";
}
}
List.List.Add(Dept);
. . .
dSQL = "INSERT INTO departments ( account_id, name) VALUES ('" + Dept.AccountID + "','" + Dept.AccountName +"')";
if (!First)
{
cmd.Parameters[0].Value = Dept.AccountID;
cmd.Parameters[1].Value = Dept.AccountName;
}
if (First)
{
cmd.Parameters.Add("#account_id",Dept.AccountID);
cmd.Parameters.Add("name",Dept.AccountName);
cmd.Prepare();
First = false;
}
if (frmCentral.CancelFetchInvDataInProgress)
{
ret = false;
return ret;
}
try
{
dbconn.DBCommand( cmd, dSQL, true );
}
. . .
public void DBCommand(SqlCeCommand cmd, string dynSQL, bool Silent)
{
SqlCeTransaction trans = GetConnection().BeginTransaction();
cmd.Transaction = trans;
try
{
cmd.ExecuteNonQuery();
trans.Commit();
}
catch (Exception ex)
{
try
{
trans.Rollback();
}
catch (SqlCeException)
{
// Handle possible exception here
}
MessageBox.Show("DBCommand Except 2"); // This one I haven't seen...
WriteDBCommandException(dynSQL, ex, Silent);
}
}
My questions are:
1) Should "?" really be used in the assignment to cmd.CommandText, or should "#" be used instead?
2) One of the "cmd.Parameters.Add()"s (account_id) uses a "#" and the other (name) doesn't. Which way is right, or is the "#" optional?
3) I can't make heads or tails of why DBCommand() is written as it is - the final two args are only used if there's an exception...???
I'm tempted to radically refactor this code, because it seems so bizarre, but since I don't really understand it, that might be a recipe for disaster...
I'm fairly certain this article will answer some of your questions:
http://msdn.microsoft.com/en-us/library/yy6y35y8.aspx
The second chart explains the difference between the named and positional (?) parameters (used in OleDb and ODBC).
I believe in the case where the ? is used, the # is optional, but I'm not sure of this. If it's working, I'd say that that IS the case.
The stuff in DBCommand appears to simply be there for logging purposes. If the exection fails, it tries to do a rollback and then logs the exception with the sql command (in dynSQL).
The ? parameter is older Access syntax.
My guess is this used to be an Access database, but someone converted it to SQL CE at some point.
Generally, SQL understands that ? parameter, but it's better to just change that while you are in there so that it is more understood.
I'm still trying to make heads & tails of all these variables. If I get it sorted out, I'll post up compilable (sp?) code.
EDIT: I had to put this into a method and work out all of the RED errors to make sure I wasn't giving you something that would not compile.
I passed it your DataSet like so, with lots of comments added:
private bool StrangeSqlCeCode(DataSet dset) {
const string ACCOUNT_ID = "AccountID";
const string DEPARTMENTS = "Departments";
const string NAME = "Name";
const string SQL_TEXT = "INSERT INTO departments (account_id, name) VALUES (#account_id, #name)";
bool ret = false;
//bool First = false; (we don't need this anymore, because we initialize the SqlCeCommand correctly up front)
using (SqlCeCommand cmd = new SqlCeCommand(SQL_TEXT)) {
// Be sure to set this to the data type of the database and size field
cmd.Parameters.Add("#account_id", SqlDbType.NVarChar, 100);
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 100);
if (-1 < dset.Tables.IndexOf(DEPARTMENTS)) {
DataTable tab = dset.Tables[DEPARTMENTS];
foreach (DataRow row in tab.Rows) {
// Check this much earlier. No need in doing all the rest if a Cancel has been requested
if (!frmCentral.CancelFetchInvDataInProgress) {
Department Dept = new Department();
if (!ret)
ret = true;
// Wow! Long way about getting the data below:
//foreach (DataColumn column in tab.Columns) {
// if (column.ColumnName == "AccountID") {
// Dept.AccountID = (string)row[column];
// } else if (column.ColumnName == "Name") {
// Dept.AccountName = !row.IsNull(column) ? row[column].ToString() : String.Empty;
// }
//}
if (-1 < tab.Columns.IndexOf(ACCOUNT_ID)) {
Dept.AccountID = row[ACCOUNT_ID].ToString();
}
if (-1 < tab.Columns.IndexOf(NAME)) {
Dept.AccountName = row[NAME].ToString();
}
List.List.Add(Dept);
// This statement below is logically the same as cmd.CommandText, so just don't use it
//string dSQL = "INSERT INTO departments ( account_id, name) VALUES ('" + Dept.AccountID + "','" + Dept.AccountName + "')";
cmd.Parameters["#account_id"].Value = Dept.AccountID;
cmd.Parameters["#name"].Value = Dept.AccountName;
cmd.Prepare(); // I really don't ever use this. Is it necessary? Perhaps.
// This whole routine below is already in a Try/Catch, so this one isn't necessary
//try {
dbconn.DBCommand(cmd, true);
//} catch {
//}
} else {
ret = false;
return ret;
}
}
}
}
return ret;
}
I wrote an overload for your DBCommand method to work with Legacy code:
public void DBCommand(SqlCeCommand cmd, string dynSQL, bool Silent) {
cmd.CommandText = dynSQL;
DBCommand(cmd, Silent);
}
public void DBCommand(SqlCeCommand cmd, bool Silent) {
string dynSQL = cmd.CommandText;
SqlCeTransaction trans = GetConnection().BeginTransaction();
cmd.Transaction = trans;
try {
cmd.ExecuteNonQuery();
trans.Commit();
} catch (Exception ex) {
try {
trans.Rollback(); // I was under the impression you never needed to call this.
// If Commit is never called, the transaction is automatically rolled back.
} catch (SqlCeException) {
// Handle possible exception here
}
MessageBox.Show("DBCommand Except 2"); // This one I haven't seen...
//WriteDBCommandException(dynSQL, ex, Silent);
}
}

How to move to next row in datatable if one row catches an error? C# 2.0

I am getting data from a mySql database and I am inserting it into another system. If a column has data in an incorrect format I log this and go to next row in the datatable. It works as expected but now if I have a search function in my method that gets some additional data and this function fails I want to immediately log this and go to next row. As it is now I just log it but it still gets inserted (without the value that didn't meet the search criteria).
My code:
private void updateCustomer()
{
MySqlConnection connection = new MySqlConnection("server=myServer;database=myDatabase;uid=myID;password=myPass");
MySqlCommand command = new MySqlCommand(#"mySelectCommand", connection);
DataTable customerTbl = new DataTable();
MySqlDataReader reader;
try
{
connection.Open();
reader = command.ExecuteReader();
if (reader.HasRows)
{
customerTbl.Load(reader);
}
reader.Close();
}
catch (Exception ex)
{
_out.error("Could not connect to mySql database");
}
finally
{
connection.Close();
}
foreach (DataRow row in customerTbl.Rows)
{
// Declare the customer variables
string customerID = Encoding.ASCII.GetString((byte[])row["Customer ID"]);
string ChildOf = row["Child of"].ToString();
// Create the customer object
Customer customer = new Customer();
customer.entityId = customerID;
if (ChildOf != "")
{
RecordRef parentRef = new RecordRef();
try
{
parentRef.internalId = searchCustomer(ChildOf);
}
catch
{
// If it fails here I want to log the customerID and then go to the next row in the datatable (could not find the internalid for ChildOf
_out.error(customerID + " was not updated. Error: invalid format Parent string");
}
finally
{
parentRef.typeSpecified = false;
customer.parent = parentRef;
}
}
// Invoke update() operation
WriteResponse response = _service.update(customer);
// Process the response
if (response.status.isSuccess)
{
}
else
{
_out.error(customerID + " was not updated. Error: " + getStatusDetails(response.status));
}
}
}
You need to remove the row in the catch block, and change the foreach loop to a backwards for loop to handle the removals.
I realized that I want to log the other failed fields as well. Maybe it's an inefficient way but I did something like:
bool findParent = true;
if (ChildOf != "")
{
try
{
RecordRef parentRef = new RecordRef();
parentRef.internalId = searchCustomer(ChildOf);
parentRef.typeSpecified = false;
customer.parent = parentRef;
}
catch
{
findParent = false;
_out.error(customerID + " was not inserted. Error: invalid format Parent string");
}
}
And then an if statement before trying to insert:
if (findPartner == true && findParent == true)
{
response = _service.add(customer);
// Process the response
if (response.status.isSuccess)
{
}
else
{
_out.error(customerID + " was not inserted. Error: " + getStatusDetails(response.status));
}
}
else
{
//_out.error(customerID + " was not updated. Error: " + getStatusDetails(response.status));
}
Use the row.HasError property.

Test if Table has at least certain Stored Procedure, else fail test c#

This test checks if only one SP ends with Insert, Load, or Save, then it's successful.
//Query to find SPs for a certain Table name
string check_SP =
"SELECT ROUTINE_NAME, ROUTINE_DEFINITION " +
"FROM INFORMATION_SCHEMA.ROUTINES " +
"WHERE ROUTINE_DEFINITION LIKE '%CLNT_" + Table_Name + "%' " +
"AND ROUTINE_TYPE='PROCEDURE'";
conn2.Open();
SqlCommand cmd_SP = new SqlCommand(check_SP, conn2);
list_SP = cmd_SP.ExecuteReader(); //Write 'check_SP' query results to 'list_SP'
while (list_SP.Read())
{
if (list_SP[0].ToString().EndsWith("Insert")
|| list_SP[0].ToString().EndsWith("Load")
|| list_SP[0].ToString().EndsWith("Save"))
{
Console.WriteLine(list_SP[0]);
test = true;
}
else
{
Console.WriteLine("Missing SP");
test = false;
break;
}
}
What I wanna do is to break the while loop whenever there is no Stored Procedure that ends with Insert, or Load, or Save. (i.e. Each table should have at least these three SPs or else the test will fail)
Leaving aside whether this is the right way to do this or not, you'll need to change your logic to check for the existence of each type of procedure individually:
bool insertExists = false;
bool loadExists = false;
bool saveExists = false;
while (list_SP.Read())
{
if (list_SP[0].ToString().EndsWith("Insert"))
{
insertExists = true;
}
if (list_SP[0].ToString().EndsWith("Load"))
{
loadExists = true;
}
if (list_SP[0].ToString().EndsWith("Save"))
{
saveExists = true;
}
if (insertExists && loadExists && saveExists)
{
Console.WriteLine("All three exist");
break;
}
}
if (!insertExists)
{
Console.WriteLine("Missing insert");
}
if (!loadExists)
{
Console.WriteLine("Missing load");
}
if (!saveExists)
{
Console.WriteLine("Missing save");
}

Categories

Resources