Getting passbok view total in grid using c# - 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];
}

Related

Capture the correct row index

How to capture line index from an excel spreadsheet? In my code I'm determining that the int i variable gets the value 4, and adds i ++, passing the variable inside the log, so that it skips the header and that is from 1 to 5 and captures the index from the next line, I am using the foreach inside my treading method and I'm working with DataRow. Can someone give me a hand?
My cod:
private System.Threading.Tasks.Task TableProcessing(IEnumerable<DataRow> dataparam, int i, User UserLogged)
{
i = 4;
Action<object> processing = (data) =>
{
/*if (NHibernate.Context.ThreadStaticSessionContext.HasBind(NhibernateHelper.SessionFactory.))*/
NHibernate.Context.ThreadStaticSessionContext.Bind(NhibernateHelper.HelpThreading().OpenSession());
foreach (var line in (IEnumerable<DataRow>)data)
{
i++;
List<Process> listProcessExisting = new List<Process>();
Process process = null;
Interested interested = new Interested();
//search for the process by the previous or current judicial number
if (!line.ItemArray[1].ToString().Equals(""))
process = aplProcess.consultPerNProcessER(line.ItemArray[1].ToString());
if (process == null)
{
if (!line.ItemArray[2].ToString().Equals(""))
process = aplProcess.consultPerNProcessER(linha.ItemArray[2].ToString());
}
//search the interested by cpf / cnpj, cpf / cnpj is an identification of the interested party.
if (line.ItemArray[7].ToString().Length == 14)
interested = aplaplInterested.ConsultPerCPF(AuxiliarCPF_CNPJ.DeformationCPF(line.ItemArray[7].ToString()));
if (line.ItemArray[7].ToString().Length == 18)
interested = aplInterested.ConsultPerCPF(HelpCPF_CNPJ.DeformationCNPJ(line.ItemArray[7].ToString()));
if (process != null)
{
//if the process is not null I search all procinter related to it.
List<ProcessInterested> listprocessinterested = aplProcessInterested.consultPerIdProcess(process.Code);
if (listprocessinterested.Exists(o => o.Interested == interested))
log.Append("The interested "+ process.Interested.Name +", entered in the line "+ (i + 1) +" was added back to the process "+ process.NumberProcessjudicial + " <br>");
setProcessInterested(process, interested, line, i);
}
else
{
//New Process - 6.3
process = new Process();
process.Interested = interested;
}
}
}
}
I was able to solve my problem as follows:
protected void importar_Click(object sender, EventArgs e)
{
DataTable Dados = new DataTable();
Dados = DadosExcel(Excel);
Dados.Columns.Add("indice", typeof(int));
int i = 1;
foreach (DataRow linha in Dados.Rows)
{
linha["index"] = i;
i++;
}
}

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!

Refresh Grid Control DevExpress

I'm polling a site and updating my datasource (SQLite table). The table gets updated correctly right after the poll.
An XPCollection is associated with the table and the XPCollection is used as the DataSource for the Grid Control.
My problem is: the Grid's data is not updated. I must open and close the application to see he new data reflected in the Grid.
I have tried all combinations of removing data source, refreshing datasource, but nothing seems to work.
Below is my code for polling and refreshing the Grid,
private async void WaitForXSeconds()
{
for (int i = 0; i < 100; i++)
{
await System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(60));
// do something after x seconds!
// Updates the DB with new/modified data
LoadDailyButton_Click(null, null);
BestGrid.DataSource = null;
BestGrid.DataSource = BestCollection;
string starttime = System.DateTime.Now.ToString();
CycleResultsListBox.Items.Add("Cycle Started : " + starttime.ToString());
}
}
Here is a partial snippet of what my class look like:
public class BestData : XPLiteObject
{
private int id;
[Key(true)]
public int Id
{
get { return id; }
set
{
id = value;
}
}
private DateTime gameDate;
public DateTime GameDate
{
get { return gameDate; }
set
{
gameDate = value;
}
}
private string hometeamName;
public string HomeTeamName
{
get { return hometeamName; }
set
{
hometeamName = value;
}
}
Any help would be appreciated, this one is causing headaches.
Did you try to call
BestGrid.DataBind(); after BestGrid.DataSource = xxx
private async void WaitForXSeconds()
{
for (int i = 0; i < 100; i++)
{
await System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(60));
// do something after x seconds!
// Updates the DB with new/modified data
LoadDailyButton_Click(null, null);
BestGrid.DataSource = null;
BestGrid.DataSource = BestCollection;
Bestgrid.DataBind();
string starttime = System.DateTime.Now.ToString();
CycleResultsListBox.Items.Add("Cycle Started : " + starttime.ToString());
}
}
Édit 1
gridControl1.BeginUpdate();
try
{
gridView1.Columns.Clear();
gridControl1.DataSource = null;
gridControl1.DataSource = <newDataSource>;
}
finally
{
gridControl1.EndUpdate();
}
For you:
for (int i = 0; i< 100; i++)
{
await System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(60));
// do something after x seconds!
// Updates the DB with new/modified data
LoadDailyButton_Click(null, null);
gridControl1.BeginUpdate();
BestGrid.DataSource = null;
BestGrid.DataSource = BestCollection;
gridControl1.EndUpdate();
string starttime = System.DateTime.Now.ToString();
CycleResultsListBox.Items.Add("Cycle Started : " + starttime.ToString());
}
The following code has fixed my problem.
private async void WaitForXSeconds()
{
for (int i = 0; i < 100; i++)
{
await System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(300));
// do something after x seconds!
// Updates the DB with new/modified data
LoadDailyButton_Click(null, null);
gridView2.CollapseAllDetails();
BestGrid.DataSource = null;
session1.DropIdentityMap();
BestCollection.Reload();
BestGrid.DataSource = BestCollection;
string starttime = System.DateTime.Now.ToString();
CycleResultsListBox.Items.Add("Cycle Started : " + starttime.ToString());
}
}
Here is the code I use to save the data;
using (var uow = new UnitOfWork(xsession.DataLayer))
{
BestData getSingleRec = new XPCollection<BestData>(uow, CriteriaOperator.Parse("[HomeTeamName]=? AND [GameDate]=?", tempStr5.ToString(), Convert.ToDateTime(gameDate))).FirstOrDefault();
getSingleRec.awayR = Convert.ToInt16(tempStr7);
getSingleRec.homeR = Convert.ToInt16(tempStr8);
getSingleRec.awayML = tempStr2;
getSingleRec.homeML = tempStr3;
getSingleRec.Save();
uow.CommitChanges();
}

Displaying the Incorrect Cost

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

IsPostBack Issue

I am trying to do a 3 tier volunteers sign up for packaging session system. First, on the page load, I get the details of certain packaging session:
if (!IsPostBack)
{
string packingID = Request.QueryString["id"];
packingIndv = packing.getPacking(packingID);
if (packingIndv == null)
{
lbl_msg.Text = "Error in getting packing session details!";
}
else
{
lbl_ID.Text = packingIndv.packingID;
lbl_date.Text = packingIndv.date.ToString("dd/M/yyyy", CultureInfo.InvariantCulture); ;
lbl_location.Text = packingIndv.location;
lbl_volunteerAvailable.Text = packingIndv.volunteerAvailable.ToString();
lbl_status.Text = packingIndv.status;
}
}
After that, volunteers can click on the join button, and the program will execute:
In presentation layer after join button is on click:
string userLogged = Session["userLogged"].ToString();
UserBLL user = new UserBLL();
string userID = user.getUserIDByName(userLogged);
PackingBLL packing = new PackingBLL();
string msg = "";
msg = packing.joinPacking(userID, lbl_ID.Text);
lbl_msg.Text = msg;
In business logic layer:
public string joinPacking(string userID, string packingID)
{
string returnMessage = "";
if(returnMessage.Length == 0)
{
Packing packing = new Packing(userID, packingID);
Boolean success = packing.checkJoinedSession();
if (success)
{
returnMessage += "Same volunteer cannot join same packing session for more than once! <br/>";
}
else
{
int nofRows = 0;
nofRows = packing.joinPacking();
if (nofRows > 0)
{
returnMessage = "Request to volunteer for packing session saved successfully.";
int successUpdate = packing.updateRemaining();
if (successUpdate > 0)
{
getPacking(packingID);
}
}
else
{
returnMessage = "Error! Please try again.";
}
}
}
return returnMessage;
}
In data access layer:
public int updateRemaining()
{
int result = 0;
using (var connection = new SqlConnection(FFTHDb.connectionString)) // get your connection string from the other class here
{
SqlCommand command = new SqlCommand("UPDATE PackingSession SET volunteerAvailable = volunteerAvailable + 1 WHERE packingID = '" + packingID + "'", connection);
connection.Open();
result = command.ExecuteNonQuery();
connection.Close();
}
return result;
}
For every join from each volunteer, the volunteer available will be increased by one. What I am trying to do is from the page load, I display the details of packaging session. Then when volunteer joins it, the volunteerAvailable will straight away increased by one. All my database works perfectly, it just wont increase the volunteer available automatically after each successful update sql statement, as in I have to refresh the browser in order to see the changes.

Categories

Resources