Guys I have a query that returns 3 values (-4.00 , -7.53 , -15.00.
I am returning these in list named ReaderResult as shown in codes,however while they are added to the list I also want to keep the total of the elements being added in the list
DataReader = DoQuery(" select oa.[OtherAmount] FROM [Biatss_PC_SRV].[Pax].[SalesDocumentOtherAmount] as oa "
+"INNER JOIN [Biatss_PC_SRV].[Pax].[SalesRelatedDocumentInformation] as rd on oa.RelatedDocumentGuid = rd.RelatedDocumentGuid "
+"INNER JOIN [Biatss_PC_SRV].[Pax].[SalesDocumentHeader] as h on rd.HdrGuid = h.HdrGuid where h.DocumentNumber = '" + txtTicketNumber.Text.ToString() + "'");
//check DataReader
if (DataReader == null)
{
DataReader.Close();
DataReader.Dispose();
}
else
{
if (DataReader.HasRows)
{
//setting variables to be used to initial values
ii = 0;
double sumOfTaxes = 0;
ReaderResult.Clear();
while (DataReader.Read())
{
//for ( ii = 0; ii < DataReader.FieldCount; ii++)
//{
if (DataReader.IsDBNull(0))
{
string CaseNull = "";
ReaderResult.Add(CaseNull);
}
else
{
//put results in LIST<>
ReaderResult.Add(Convert.ToString(DataReader.GetDecimal(0)));
//double sumLaSa =+ Convert.ToDouble(ReaderResult.Last()); VALUE HERE IS ONLY THE LAST OF THE 3 NOT THE SUM
//sumOfTaxes =+ Convert.ToDouble(DataReader.GetDecimal(0));
//double sumLaSa =+ Convert.ToDouble(ReaderResult.Last().Last()); ERROR I GET HERE says cannont convert char to double
myTextboxListForAmounts[ii].Text = Convert.ToString(DataReader.GetDecimal(0));
// }
if (ii > 6)
{
//make txtXT visible and display summed up amount in it
lblXT.Visible = true;
txtXT.Visible = true;
txtXT.Text = Convert.ToString(sumOfTaxes);
}
ii++;
}
}
}
else
{
DataReader.Close();
DataReader.Dispose();
}
DataReader.Close();
DataReader.Dispose();
}
How can I get the sum of the values returned please ?
Solved the problem.
The aim is reached using the solution ignited by Corak.
sumOfTaxes =+ Convert.ToDouble(DataReader.GetDecimal(0));
modified to
sumOfTaxes += Convert.ToDouble(DataReader.GetDecimal(0)); (+= instead of =+)
enter code here
Related
I have this code that copy selected rows from one grid to another
private void btnAddEmployee_Click(object sender, EventArgs e)
{
LayoutControl lc = new LayoutControl();
lc.Dock = DockStyle.Top;
LookUpEdit userShift = new LookUpEdit();
userShift.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;
userShift.Properties.DataSource = paint.GetShiftTime();
userShift.Properties.DisplayMember = "ShiftTime";
userShift.Properties.ValueMember = "id";
userShift.Properties.ShowHeader = false;
var date = DateTime.Now;
if (8 < date.Hour && date.Hour < 16)
{
userShift.EditValue = 1;
}
else if (16 < date.Hour && date.Hour < 24)
{
userShift.EditValue = 2;
}
else
{
userShift.EditValue = 3;
}
lc.AddItem(Resources.workingHours, userShift).TextVisible = true;
lc.Height = 50;
this.Controls.Add(lc);
this.Dock = DockStyle.Top;
int[] selectedRows = gridView4.GetSelectedRows();
for(int n=0;n< selectedRows.Length;n++)
//foreach (int index in selectedRows)
{
if (DevExpress.XtraEditors.XtraDialog.Show(lc, Resources.options, MessageBoxButtons.OKCancel) == DialogResult.OK)
{
//Prevent duplicate data
for (int i = 0; i < gridView5.RowCount; i++)
{
if (gridView4.GetRowCellValue(gridView4.FocusedRowHandle, "Matricule").ToString() == gridView5.GetRowCellValue(i, "Matricule").ToString())
{
XtraMessageBox.Show(Resources.employeeAlreadyAdded, Resources.error, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
}
DataRow r = EmplDT.NewRow();
r[0] = gridView4.GetRowCellValue(gridView4.FocusedRowHandle, "Matricule").ToString();
r[1] = gridView4.GetRowCellValue(gridView4.FocusedRowHandle, "Employé").ToString();
r[2] = userShift.Text;
r[3] = userShift.EditValue;
r[4] = txtDate.EditValue;
EmplDT.Rows.Add(r);
this is my code to create Columns in gridview 5
DataTable EmplDT = new DataTable();
void CreateEmployeeTable()
{
EmplDT.Columns.Add("Matricule");
EmplDT.Columns.Add("Employé");
EmplDT.Columns.Add("Heure");
EmplDT.Columns.Add("idShiftTime", typeof(Int32));
EmplDT.Columns.Add("Date", typeof(DateTime));
gridControl5.DataSource = EmplDT;
gridView5.Columns["idShiftTime"].Visible = false;
gridView5.Columns["Date"].Visible = false;
}
i have two problems in this code:
the first one is when i run the code it only add the first record and then i get error message of duplicate .
the second one i want to show layout control only the first time.
thanks in advance and sorry for my english.
Looping thru selected rows from a devexpress gridview and getting a row can be much simpler like this
int[] selectedRows = gridView4.GetSelectedRows();
for (int i = 0; i < selectedRows.Length; i++)
{
// Get a DataRow and fill it with all values from the this selected row
// This is where you went wrong, you kept using only the first selected row
DataRow rowGridView4 = (gridView4.GetRow(selectedRows[i]) as DataRowView).Row;
// Do a check for doubles here
DataRow[] doubles = EmplDT.Select("Matricule = '" + rowGridView4[0].ToString() +"'");
if (doubles.Length > 0)
{
XtraMessageBox.Show(Resources.employeeAlreadyAdded, Resources.error, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// fix for error "This row already belongs to another table"
DataRox row = EmplDT.NewRow();
row[0] = rowGridView4[0];
row[1] = rowGridView4[1];
row[2] = userShift.Text;
row[3] = userShift.EditValue;
row[4] = txtDate.EditValue;
EmplDT.Rows.Add(row);
}
Please note that with testing for doubles at this place will cause all records to be copied until a duplicate is found. So after your error message there might be some records copied and some not.
Is that how you intended this ?
I would leave out the error message and just skip duplicate records. You can still show a message with howmany records where copied if you want.
int[] selectedRows = gridView4.GetSelectedRows();
for (int i = 0; i < selectedRows.Length; i++)
{
// Get a DataRow and fill it with all values from the this selected row
// This is where you went wrong, you kept using only the first selected row
DataRow rowGridView4 = (gridView4.GetRow(selectedRows[i]) as DataRowView).Row;
// Do a check for doubles here
DataRow[] doubles = EmplDT.Select("Matricule = '" + rowGridView4[0].ToString() + "'");
if (doubles.Length == 0)
{
// fix for error "This row already belongs to another table"
DataRox row = EmplDT.NewRow();
row[0] = rowGridView4[0];
row[1] = rowGridView4[1];
row[2] = userShift.Text;
row[3] = userShift.EditValue;
row[4] = txtDate.EditValue;
EmplDT.Rows.Add(row);
}
}
I'm still learning in programming
I'm trying to get customer data in list. So I can get the value from the index, but it only can get the first customer. the index won't increment, I'm still confusing, I have already move the variable for increment the index won't work, maybe my logic isn't right. here's the code, tell me where is not right..?? thank you for you help and explanation
public void getJamVSpot()
{
var listJamAwal = new List<String>();
var listJamAkhir = new List<String>();
var listNota = new List<int>();
DateTime tglSewa = dtp_tglSewa.Value.Date;
int r = 0;
String ja = String.Empty;
String jb = String.Empty;
int n = 0;
int indexUp = 0;
if (dtp_tglSewa.Value.Date == jl.getTglJadwalVspot(tglSewa, lap) && rdb_Lapangan_VSpot.Checked == true || rdb_rumputSintetis.Checked == true)
{
IEnumerator<String> jAwal = jl.getJamAwalbyDate(tglSewa, lap);
while (jAwal.MoveNext())
{
listJamAwal.Add(jAwal.Current);
}
IEnumerator<String> jAkhir = jl.getJamAkhirbyDate(tglSewa, lap);
while (jAkhir.MoveNext())
{
listJamAkhir.Add(jAkhir.Current);
}
IEnumerator<int> nota = jl.getNota(tglSewa, lap);
while (nota.MoveNext())
{
listNota.Add(nota.Current);
}
ja = listJamAwal[indexUp];
jb = listJamAkhir[indexUp];
n = listNota[indexUp];
int count = jl.countNota(n);
String penyewa = jl.getNamaPenyewa(n);
String no_kontak = jl.getNomorKontak(n);
String status = jl.getStatusSewa(n);
for (int i = 1; i <= count; i++)
{
foreach (DataGridViewRow row in dgv_Jadwal_Sewa.Rows)
if (row.Cells[0].Value.ToString().Equals(ja))
{
r = row.Index;
row.Cells[2].Value = penyewa;
row.Cells[3].Value = no_kontak;
row.Cells[4].Value = status;
if (ja != jb)
{
ja = jl.getJamAkhirbyJamAwal(ja);
row.Cells[2].Value = penyewa;
row.Cells[3].Value = no_kontak;
row.Cells[4].Value = status;
//dgv_Jadwal_Sewa.Rows[r].Selected = true;
}
break;
}
}
} indexUp++;
}
When you increment the indexUp variable you aren't using it anymore.
In your code you are just recovering the first item (0), doing some stuff with this value (in the loops) and exits.
For example, you can wrap your stuff with this loop:
for (int indexUp = 0; indexUp < listJamAwal.Count; indexUp++)
{
ja = listJamAwal[indexUp];
jb = listJamAkhir[indexUp];
n = listNota[indexUp];
int count = jl.countNota(n);
String penyewa = jl.getNamaPenyewa(n);
String no_kontak = jl.getNomorKontak(n);
String status = jl.getStatusSewa(n);
for (int i = 1; i <= count; i++)
{
foreach (DataGridViewRow row in dgv_Jadwal_Sewa.Rows)
{
if (row.Cells[0].Value.ToString().Equals(ja))
{
r = row.Index;
row.Cells[2].Value = penyewa;
row.Cells[3].Value = no_kontak;
row.Cells[4].Value = status;
if (ja != jb)
{
ja = jl.getJamAkhirbyJamAwal(ja);
row.Cells[2].Value = penyewa;
row.Cells[3].Value = no_kontak;
row.Cells[4].Value = status;
//dgv_Jadwal_Sewa.Rows[r].Selected = true;
}
break;
}
}
}
}
There are two problems with how you access the items:
You assign the variables outside the loop. That will get the values that the index points to at that moment, and changing the index variable later doesn't change what's assigned to the variables. You have to assign the variables inside the loop, except the count variable of course which you need before the loop starts.
You are incrementing the indexUp variable after the loop, when you have no use for it any more. You have to put that inside the loop so that it can be used in the next iteration to read new values into the variables.
I dont see any point of using first loop with "i" and then second with foreach. Its totally wrong - you are doing the same thing "count" times!
You also need to change penyewa, no_kontak, status because you are using same values inside loop
And in addition, I have never seen so confusing and unclear variable naming, you should change it if you want some else to use it :D
I Have a DataGridView, with columns Item, description, quantity, rate & total.
I have two types of items, one item have vapasi == yes (vapasi is a kind of deposite amount), & another item have vapasi == No.I want to calculate the sum of 'total' column by differentiating items with vapasi & items without vapasi, & want to display this calculated total into two respective textboxes that is 'txtboxwithvapasi', n 'txtboxwithoutvapasi' which are there after the grid.I did following code :
private void grdPurchase_CellEndEdit_1(object sender, DataGridViewCellEventArgs e)
{
try
{
try
{
string value = grdPurchase.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
if (e.ColumnIndex == 2)
{
int val = int.Parse(value);
quantity = val;
}
if (e.ColumnIndex == 4)
{
float val = float.Parse(value);
total = val;
if (vapasi1 == "Yes")
{
vtot += total; //vtot=0+10
txt_forvapasitotal.Text = vtot.ToString(); //10
float vapsitot =float.Parse(txt_forvapasitotal.Text);
float vapsicalculate = (vapsitot * a);
float tax = vapsicalculate / 100;
float with_vapasi = vtot + tax;
txt_withvapasi.Text =Convert.ToString(with_vapasi);
}
else
{
nvtot = 0;
for (int i = 0; i < grdPurchase.Rows.Count; i++)
{
if (vapasi1 == "No")
{
if (grdPurchase.Rows[e.RowIndex].Cells[3].Selected == true)
{
nvtot += float.Parse(grdPurchase[4, i].EditedFormattedValue.ToString());
txt_withoutvapasitot.Text = nvtot.ToString();
}
}
}
}
txt_vapasiincludedtot.Text =(float.Parse(txt_withvapasi.Text) +float.Parse(txt_withoutvapasitot.Text)).ToString();
}
if (e.ColumnIndex == 1)
{
int val = int.Parse(value);
materialid = val;
string vapasi = "Select material_vapasi from tbl_material_master where active_flag=1 AND material_id =" + materialid + "";
SqlCommand cmd = new SqlCommand(vapasi, con);
sdr = cmd.ExecuteReader();
if (sdr.HasRows)
{
while (sdr.Read())
{
vapasi1 = sdr["material_vapasi"].ToString();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
grdPurchase.Columns[3].ReadOnly = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
Problem is:-when I am selecting item with vapasi in first row & in second row item without vapasi , its working properly.But if i Select any item at third row ,then its doing sum of all the three items in 'txtboxwithoutvapasi' without differentiating items.
You need to keep track of vapasi being "Yes" or "No" for each row in the grid, but you are using a single variable. Can't you add this column to the grid (as a hidden column if you don't want to show this to the user)? Then whenever you need to calculate the totals you simply iterate through the grid rows and check the vapasi column in stead of the vapasi1 variable.
I am trying to check for ascending order in this array
But not sure how to use a foreach
foreach (double d in dSize)
{
if (dSize.ToString() != null)
{
double dSize1;
string str1 = dSize.ToString();
bool success1 = double.TryParse(str1, out dSize1);
if ( dSize < 0.0)
{
errMsg1 = " data grid should contain number >= 0";
}
//else
//{
// errMsg1 = " data grid must be entered";
//}
}
*if (inputs.dSize[rowCount] <= inputs.dSize[rowCount - 1])
{
errMsg = "value in row " + (rowCount + 1) + " should be greater than the value in row " + rowCount;
}
}*
swRpt.WriteLine(errMsg);
}
I've done the second part using a for loop. Would like to change it to a foreach
You just need to remember the previous value from one iteration to the next. The issue with using foreach for this (as opposed to the raw iterator) is that you need a special case for the first value:
Double lastDouble = null;
foreach(double d in dSize) {
if ((lastDouble != null) && (lastDouble > d)) {
errMsg = "value out of sequence";
break;
}
lastDouble = d;
}
but then you've lost the row number for the error. You could also prime your last value from the first entry and skip one using LINQ
double lastDouble = dSize.First();
foreach(double d in dSize.Skip(1)) {
if (lastDouble > d) {
errMsg = "value out of sequence";
break;
}
lastDouble = d;
}
Why not...
for(int i = dSize.Length-1; i>=0;i--)
{
double d = dSize[i];
...
...
...
}
This application works as if you were playing the lottery, you pick 5 numbers from a comboBox, click a button to generate the 5 key numbers and then you press another button to check the results (after you introduce the prize monei on the textbox below, AKA "prémio").
The button that does the checking is the highlighted one Verificar Prémio.
Here's it's code:
private void button5_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" && textBox1.Text!="Prémio em €")
{
int contador = 0;
for (int i = 1; i <= 5; i++)
{
string posicao = i.ToString();
for (int c = 1; c <= 5; c++)
{
string poschave = c.ToString();
if (listBox1.Items.IndexOf(posicao) ==
listBox2.Items.IndexOf(poschave))
{
contador = contador + 1;
}
}
i = int.Parse(posicao);
double valor;
double premio = double.Parse(textBox1.Text);
if (contador == 5)
{
MessageBox.Show(" Parabens ganhou o 1º premio acertou 5 números
o seu prémio é de " + premio + "€");
}
else
{
if (contador == 4)
{
valor = premio * 0.75;
MessageBox.Show(" Acertou 4 numeros o seu premio é: " +
valor + "€");
}
else
{
if (contador == 3)
{
valor = premio * 0.5;
MessageBox.Show("Acertou 3 numeros o seu premio é: " +
valor + "€");
}
else
if (contador <= 2)
{
MessageBox.Show(" Infelizmente nao ganhou,
nada tente outra vez");
}
}
}
}
}
}
Whatever I do, it always shows the messageBox saying I got all 5 correct...
EDIT:
listBox1 is the one on the left, (3, 9, 17, 20, 10), you choose them from the combobox and when you Click "Apostar" it is added to it.
listBox2 is the box on the right.
EDIT2:
By replacing
for (int c = 1; c <= 5; c++)
{
string poschave = c.ToString();
if (listBox1.Items.IndexOf(posicao) == listBox2.Items.IndexOf(poschave))
{
contador = contador + 1;
}
}
with
foreach (var item in listBox1.Items)
{
// Convert it to string to avoid object reference comparison. Not 100%
// sure if this is needed
string value = item.ToString();
if (listBox2.Items.Contains(value))
contador++;
}
The error doesnt show anymore however it still isnt working properly, my guess is that the program is checking if they match, then get the result, therefore it always show "you won nothing" 5 times in a row...
How can I fix this?
I don't understand Spanish(?) so it's very hard to understand your code (please use english variable names, even if you have a localized UI)
However, one cause of the problem could be this line:
listBox1.Items.IndexOf(posicao) == listBox2.Items.IndexOf(poschave)
In case neither posicao or poschave is found in their respective listboxes, -1 will be returned and the expression will be true (i.e. contador will be incremented). I'm guessing this is not the desired behavior.
If you instead want to check if an item in the left listbox is also available in the right, then you could do:
void Button_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox1.Text == "Prémio em €")
return;
int numMatches = 0;
foreach (var item in listBox1.Items)
{
if (listBox2.Items.Contains(item))
numMatches++;
}
// numMatches will now contain the number of elements in the left
// listbox that also exist in the right listbox
if (numMatches > 2)
{
double premio = Double.Parse(textBox1.Text);
double prize = 0;
if (numMatches == 5)
prize = premio * 1.0;
if (numMatches == 4)
prize = premio * 0.75;
else
prize = premio * 0.5;
// Use string.Format() instead to get fancier formatting of numbers
Messagebox.Show ("Sweet, you got " + numMatches + " out of 5 correct numbers. Your prize is " + prize + "€");
}
else
{
MessageBox.Show("Sorry, not enough matches - you win nothing!");
}
}
EDIT:
The reason you get 5 message boxes is because you have the call to Messagebox.Show() inside a for loop that loops five times. I've updated the code sample above to do what I think you want your button callback to do
Your source is way too complicated, you have two loops, one integer > string followed by string > integer... try this:
int count = 0;
for (int i = 0; i < 5; i++)
{
if (listBox2.Items.IndexOf(listBox1.Items[i]) > 0)
{
count++;
}
}
// count is 0 - 5
You only check for 5 numbers of the left ListBox if it is in the right ListBox.