query is not giving correct values - c#

SELECT
machine_id, operator_id, member_id, card_id, name, paid_amount, due_amount,
paid_date, phone_number, #curRow := #curRow + 1 AS row_number
FROM
transaction
JOIN
(SELECT #curRow := 0) r where card_id='c1' order by Row_number desc limit 3 ;
When I run this in workbench it returns the last 3 records. But in my code it returns only 2 records. What is the problem?
Here is the c# code:
String query3 = "SELECT machine_id,operator_id,member_id,card_id,name,paid_amount,due_amount,paid_date,phone_number ,#curRow := #curRow + 1 AS row_number FROM transaction JOIN (SELECT #curRow := 0) r where card_id=#card order by Row_number desc limit 4 ";
MySqlCommand command3 = new MySqlCommand(query3, con);
command3.Parameters.AddWithValue("#card", cardid);
using (MySqlDataReader rdr3 = command3.ExecuteReader())
{
if (rdr3.Read())
{
while (rdr3.Read())
{
if (count == 1)
{
AMT1 = Convert.ToDecimal(rdr3["paid_amount"].ToString());
TOT1 = rdr3["paid_date"].ToString();
}
if (count == 2)
{
AMT2 = Convert.ToDecimal(rdr3["paid_amount"].ToString());
TOT2 = rdr3["paid_date"].ToString();
}
if (count == 3)
{
AMT3 = Convert.ToDecimal(rdr3["paid_amount"].ToString());
TOT3 = rdr3["paid_date"].ToString();
}
count++;
}
Response.Write("$AMT1=" + AMT1 + "|TOT1=" + TOT1 + "|AMT2=" + AMT2 + "|TOT2=" + TOT2 + "|AMT3=" + AMT3 + "|TOT3=" + TOT3 + "|TS=1#");
}

You use Read() twice at the beginning and you skip the first record this way. Remove the one from if:
if (rdr3.Read())
You need just:
using (MySqlDataReader rdr3 = command3.ExecuteReader())
{
while (rdr3.Read())
{
if (count == 1)
{
AMT1 = Convert.ToDecimal(rdr3["paid_amount"].ToString());
TOT1 = rdr3["paid_date"].ToString();
}
if (count == 2)
{
AMT2 = Convert.ToDecimal(rdr3["paid_amount"].ToString());
TOT2 = rdr3["paid_date"].ToString();
}
if (count == 3)
{
AMT3 = Convert.ToDecimal(rdr3["paid_amount"].ToString());
TOT3 = rdr3["paid_date"].ToString();
}
count++;
}
Response.Write("$AMT1=" + AMT1 + "|TOT1=" + TOT1 + "|AMT2=" + AMT2 + "|TOT2=" + TOT2 + "|AMT3=" + AMT3 + "|TOT3=" + TOT3 + "|TS=1#");
}

Use if (rdr3.HasRows) instead of if (rdr3.Read())
using (MySqlDataReader rdr3 = command3.ExecuteReader())
{
if (rdr3.HasRows)
{
while (rdr3.Read())
{
if (count == 1)
{
AMT1 = Convert.ToDecimal(rdr3["paid_amount"].ToString());
TOT1 = rdr3["paid_date"].ToString();
}
if (count == 2)
{
AMT2 = Convert.ToDecimal(rdr3["paid_amount"].ToString());
TOT2 = rdr3["paid_date"].ToString();
}
if (count == 3)
{
AMT3 = Convert.ToDecimal(rdr3["paid_amount"].ToString());
TOT3 = rdr3["paid_date"].ToString();
}
count++;
}
}
Else
{
Response.Write("No rows found.");
}
Response.Write("$AMT1=" + AMT1 + "|TOT1=" + TOT1 + "|AMT2=" + AMT2 + "|TOT2=" + TOT2 + "|AMT3=" + AMT3 + "|TOT3=" + TOT3 + "|TS=1#");
}

Related

Converting a program from console to windows form C#

I am trying to convert a program from console to windows form but the problem is that the output is not showing on my textbox. My program is that user inputs how many number of rows.
int n = int.Parse(textbox1.Text);
int counter1 = 1,counter2 = 1,size = n + n -1;
for(int i = 0;i<size;i++){
for(int j = 0;j<size;j++){
if(i<n-1){
if(j<n-1){
if(i == j){
textBox2.Text = "{0} " + counter1;
counter1++;}
else{
textBox2.Text = " ";
} }
else{
if(i + j == size-1){
textBox2.Text = "{0} " + counter2;
counter2++;}
else{
textBox2.Text = " ";
}
} }
else if(i == n- 1 && j == n-1){
textBox2.Text = "{0} " + counter1;
counter1--;
counter2--; }
else if(i == n-1 && j != n-1){
textBox2.Text = " ";
}
else if(i > n-1){
if(j>n-1){
if(i == j){
textBox2.Text = "{0} " + counter1;
counter1--;
}
else{
textBox2.Text = " ";
} }
else
{
if(i + j == size-1){
textBox2.Text = "{0} " + counter2;
counter2--;
}
else{
textBox2.Text = " ";
}
} } }
textBox2.Text = " ";
}
The program is to display the input x number pattern. Thanks in advance.
You are resetting the text of textBox2 every time. You should use the += operator instead of =.
Side note: You should also use the special '\n' character when you need a new line.

Resolve duplicate issues with while loops and dictionaries

I have a list of items that are determined by what a player enters into several input fields, but for the sake of this example, let's say that it contains "a", "b", "c", "d", and "e". These are then sorted into a dictionary with a list of numbers as the values (unimportant). I then randomize the dictionary with two different randomizer variables (i and j), for the sake of taking two objects from the dictionary and displaying them to the screen, so the player can press various associated buttons. This goes on until x amount of turns have passed. The main problem I'm having is the prevention of semi-duplicates, such as "a b" and "b a" from appearing.
I have tried entering inserting both the randomized pair and its semi-duplicate into another dictionary and then using while loop statements preventing any pairs from that dictionary from appearing. Unfortunately, this hasn't worked.
Below is my code.
public void Start() {
finalList = new Dictionary<string, int>();
for (index = 0; index < allNumbers; index++)
{
finalList.Add(itemList[index], valueList[index]);
Debug.Log(finalList[index.ToString()]);
}
}
public void Update() {
choose();
}
public void choose() {
duplicates = new Dictionary<string, string>();
duplicates.Clear();
while (rounds < insertNum) {
key = "(" + itemList[i].ToString() + " " + itemList[j].ToString() + ")";
reverseKey = "(" + itemList[j].ToString() + " " + itemList[i].ToString() + ")";
while (j == i || (duplicates.ContainsKey(key) || duplicates.ContainsKey(reverseKey))) {
i = UnityEngine.Random.Range(0, allNumbers - 1);
j = UnityEngine.Random.Range(0, allNumbers - 1);
key = "(" + itemList[i].ToString() + " " + itemList[j].ToString() + ")";
reverseKey = "(" + itemList[j].ToString() + " " + itemList[i].ToString() + ")";
Debug.Log("(new keys " + key + ", " + reverseKey + ")");
//break;
} while (j == i || (duplicates.ContainsKey(key) && duplicates.ContainsKey(reverseKey)))
{
i = UnityEngine.Random.Range(0, allNumbers - 1);
j = UnityEngine.Random.Range(0, allNumbers - 1);
key = "(" + itemList[i].ToString() + " " + itemList[j].ToString() + ")";
reverseKey = "(" + itemList[j].ToString() + " " + itemList[i].ToString() + ")";
Debug.Log("(new keys " + key + ", " + reverseKey + ")");
}while (j == i && (duplicates.ContainsKey(key) || dupes.ContainsKey(reverseKey))) {
i = UnityEngine.Random.Range(0, allNumbers - 1);
j = UnityEngine.Random.Range(0, allNumbers - 1);
key = "(" + itemList[i].ToString() + " " + itemList[j].ToString() + ")";
reverseKey = "(" + itemList[j].ToString() + " " + itemList[i].ToString() + ")";
Debug.Log("(new keys " + key + ", " + reverseKey + ")");
}
while (j == i && (duplicates.ContainsKey(key) && duplicates.ContainsKey(reverseKey))) {
i = UnityEngine.Random.Range(0, allNumbers - 1);
j = UnityEngine.Random.Range(0, allNumbers - 1);
key = "(" + itemList[i].ToString() + " " + itemList[j].ToString() + ")";
reverseKey = "(" + itemList[j].ToString() + " " + itemList[i].ToString() + ")";
Debug.Log("(new keys " + key + ", " + reverseKey + ")");
}
duplicates.Add(key, "1"); // the one is just a filler variable
duplicates.Add(reverseKey, "1");
if (buttonOneBool) { //this is in another script, ignore
finalList[itemList[i].ToString()] = valueList[i] += 2;
finalList[itemList[j].ToString()] = valueList[j] -= 2;
i = UnityEngine.Random.Range(0, n - 1);
j = UnityEngine.Random.Range(0, n - 1);
} else if (buttonTwoBool) {
finalList[itemList[i].ToString()] = valueList[i] -= 2;
finalList[itemList[j].ToString()] = valueList[j] += 2;
i = UnityEngine.Random.Range(0, n - 1);
j = UnityEngine.Random.Range(0, n - 1);
} else if (buttonThreeBool) {
finalList[itemList[i].ToString()] = valueList[i] -= 1;
finalList[itemList[j].ToString()] = valueList[j] -= 1;
i = UnityEngine.Random.Range(0, n - 1);
j = UnityEngine.Random.Range(0, n - 1);
} else if (buttonFourBool) {
finalList[itemList[i].ToString()] = valueList[i] += 1;
finalList[itemList[j].ToString()] = valueList[j] += 1;
i = UnityEngine.Random.Range(0, n - 1);
j = UnityEngine.Random.Range(0, n - 1);
}
break;
}
The simplest way to fix this is to guarantee i < j. When selecting a new i and j like this:
i = UnityEngine.Random.Range(min, max);
j = UnityEngine.Random.Range(min, max);
Instead do this:
i = UnityEngine.Random.Range(min, max - 1);
j = UnityEngine.Random.Range(i + 1, max);
Doing this rules out the possibility of selecting a "mirror image" of a previous case and also avoids the "i == j" case.
After these modifications your choose() function should look something like this:
public void choose()
{
duplicates = new HashSet<string>();
while (rounds < insertNum)
{
key = "(" + itemList[i].ToString() + " " + itemList[j].ToString() + ")";
while (duplicates.Contains(key))
{
i = UnityEngine.Random.Range(0, allNumbers - 2);
j = UnityEngine.Random.Range(i + 1, allNumbers - 1);
key = "(" + itemList[i].ToString() + " " + itemList[j].ToString() + ")";
}
duplicates.Add(key); // the one is just a filler variable
if (buttonOneBool) { //bool definitions are in another script, ignore
finalList[itemList[i].ToString()] = valueList[i] += 2;
finalList[itemList[j].ToString()] = valueList[j] -= 2;
i = UnityEngine.Random.Range(0, n - 1);
j = UnityEngine.Random.Range(0, n - 1);
} else if (buttonTwoBool) {
finalList[itemList[i].ToString()] = valueList[i] -= 2;
finalList[itemList[j].ToString()] = valueList[j] += 2;
i = UnityEngine.Random.Range(0, n - 1);
j = UnityEngine.Random.Range(0, n - 1);
} else if (buttonThreeBool) {
finalList[itemList[i].ToString()] = valueList[i] -= 1;
finalList[itemList[j].ToString()] = valueList[j] -= 1;
i = UnityEngine.Random.Range(0, n - 1);
j = UnityEngine.Random.Range(0, n - 1);
} else if (buttonFourBool) {
finalList[itemList[i].ToString()] = valueList[i] += 1;
finalList[itemList[j].ToString()] = valueList[j] += 1;
i = UnityEngine.Random.Range(0, n - 1);
j = UnityEngine.Random.Range(0, n - 1);
}
break;
}
}
You can get two random indexes to a list using code below. The code uses integer as the list type and will work with any type.
List<int> randomList = itemList.Select((x, i) => new { index = i, rand = rand.Next() }).OrderBy(x => x.rand).Select(x => x.index).ToList();
Then the two random indexes into the list are randomList[0] and randomList[1]. The code assigns a random number to each index i of the list. To get the two items from the list use itemList[randomList[0]] and itemList[randomList[1]]. The code assumes there are at least two items in the original list ItemList[].
If your original list has duplicates than you need to use Distinct() as shown in code below
List<int> distinctList = itemList.Distinct().ToList();
List<int> randomList = distinctList.Select((x, i) => new { index = i, rand = rand.Next() }).OrderBy(x => x.rand).Select(x => x.index).ToList();

Testing all cells in datagridview

for (int i = 0; i < metroGrid1.Rows.Count; i++)
{
if (metroGrid1.Rows[i].Cells[0].Value.ToString() == radGridView1.SelectedRows[0].Cells[0].Value.ToString())
{
counter = i;
metroGrid1.Rows[counter].Cells[2].Value = Convert.ToInt32(metroGrid1.Rows[counter].Cells[2].Value) + radSpinEditor1.Value;
MessageBox.Show("for loop");
}
else
{
metroGrid1.Rows.Add(radGridView1.SelectedRows[0].Cells[0].Value.ToString(), radGridView1.SelectedRows[0].Cells[1].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[2].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[3].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[4].Value.ToString(), radSpinEditor1.Value, decimal.Round(prodamt, 2), decimal.Round(prodtotamt, 2));
totamt += prodtotamt;
metroLabelTotalamt.Text = (string.Format("{0:#,###0.00}", totamt));
radSpinEditor1.Value = 1;
MessageBox.Show("else ");
}
}
Shouldn't that be? Since you yourself adding rows to your gridview by calling Add() method as can be seen in your posted code
metroGrid1.Rows.Add(radGridView1.SelectedRows[0].Cells[0].Value.ToString(),
No idea since I don't know your requirement but to me it feels like you wanted to have the other part as else block.
for (int i = 0; i < metroGrid1.Rows.Count; i++)
{
if (metroGrid1.Rows[i].Cells[0].Value.ToString() == radGridView1.SelectedRows[0].Cells[0].Value.ToString())
{
counter = i;
metroGrid1.Rows[counter].Cells[2].Value = Convert.ToInt32(metroGrid1.Rows[counter].Cells[2].Value) + radSpinEditor1.Value;
MessageBox.Show("for loop");
}
else
{
metroGrid1.Rows.Add(radGridView1.SelectedRows[0].Cells[0].Value.ToString(), radGridView1.SelectedRows[0].Cells[1].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[2].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[3].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[4].Value.ToString(), radSpinEditor1.Value, decimal.Round(prodamt, 2), decimal.Round(prodtotamt, 2));
totamt += prodtotamt;
metroLabelTotalamt.Text = (string.Format("{0:#,###0.00}", totamt));
radSpinEditor1.Value = 1;
MessageBox.Show("else ");
}
}

Text file is always blank

I have made this timer class and when its end timer function is called it is supposed to write a text file however it only seems to create a blank file every time. any ideas why? i have checked and the date modified is always the time i last ran the function.
public class Timer100NanoSeconds
{
long startTick;
List<Tuple<string, long>> stepTicks;
readonly string functionName;
int timesRan;
public Timer100NanoSeconds(string name)
{
functionName = name;
StartNew();
}
public void StartNew()
{
timesRan = 0;
startTick = DateTime.Now.Ticks;
stepTicks = new List<Tuple<string, long>>();
}
public void AddStep(string temp)
{
stepTicks.Add(new Tuple<string, long>(temp, DateTime.Now.Ticks));
}
public void counterForTimesRan(int ran)
{
timesRan = ran;
}
public void EndTimer()
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(functionName + ".txt"))
{
file.WriteLine("Ran " + timesRan + " Times");
for (int i = 0; i < stepTicks.Count; i++)
{
if (i == 0)
{
if (stepTicks[i].Item2 - startTick != 0)
{
file.WriteLine(("" + (stepTicks[i].Item2 - startTick)).PadLeft(15, ' ') + " , " + stepTicks[i].Item1.Trim());
}
}
else
{
if (stepTicks[i].Item2 - stepTicks[i - 1].Item2 != 0)
{
file.WriteLine(("" + (stepTicks[i].Item2 - stepTicks[i - 1].Item2)).PadLeft(15, ' ') + " , " + stepTicks[i].Item1.Trim());
}
}
}
}
}
public void EndTimer(bool showZero)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(functionName + ".txt"))
{
for (int i = 0; i < stepTicks.Count; i++)
{
if (showZero)
{
if (i == 0)
{
file.WriteLine(("" + (stepTicks[i].Item2 - startTick)).PadLeft(15, ' ') + " , " + stepTicks[i].Item1.Trim());
}
else
{
file.WriteLine(("" + (stepTicks[i].Item2 - stepTicks[i - 1].Item2)).PadLeft(15, ' ') + " , " + stepTicks[i].Item1.Trim());
}
}
else
{
if (i == 0)
{
if (stepTicks[i].Item2 - startTick != 0)
{
file.WriteLine(("" + (stepTicks[i].Item2 - startTick)).PadLeft(15, ' ') + " , " + stepTicks[i].Item1.Trim());
}
}
else
{
if (stepTicks[i].Item2 - stepTicks[i - 1].Item2 != 0)
{
file.WriteLine(("" + (stepTicks[i].Item2 - stepTicks[i - 1].Item2)).PadLeft(15, ' ') + " , " + stepTicks[i].Item1.Trim());
}
}
}
}
}
}
}

c# error with dataset update

I have list of type string with name temp1 in this list i have a group of words for each word im calculating N00,N01,N10,N11,MI at last it is throwing exception Update unable to find TableMapping['sample'] or DataTable 'sample'..plz help
DataSet dsSelectAll = new DataSet();
SqlCommand cmdSelectAll = new SqlCommand("select * from sample", con);
SqlDataAdapter daSelectAll = new SqlDataAdapter(cmdSelectAll);
SqlCommandBuilder scb = new SqlCommandBuilder(daSelectAll);
daSelectAll.FillSchema(dsSelectAll,SchemaType.Mapped, "sample");
foreach (string ri in temp1)
{
//for (int a3 = 0; a3 < ssl.Count; a3++)
{
cmdT.CommandText = #"SELECT * FROM [vijay].[dbo].[sample] where keyword in ('y','" + ri + "')";
// ds.Tables.Clear();
da.Fill(ds);
// row 1 :: 1 0 0 1 0 0
// row 2:: 2 7 0 0 0 1
int N00 = 0;
int N01 = 0;
int N10 = 0;
int N11 = 0;
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
// N00
if (ds.Tables[0].Rows[0][i].ToString() == "0")
{
if (ds.Tables[0].Rows[1][i].ToString() == "0")
{
N00++;
}
}
// N01
if (ds.Tables[0].Rows[0][i].ToString() == "1")
{
if (ds.Tables[0].Rows[1][i].ToString() == "0")
{
N01++;
}
}
// N10
if (ds.Tables[0].Rows[0][i].ToString() == "0")
{
if ((ds.Tables[0].Rows[1][i].ToString()) !="0")
{
N10++;
}
}
// N11
if (ds.Tables[0].Rows[0][i].ToString() == "1")
{
if (ds.Tables[0].Rows[1][i].ToString()!="0")
{
N11++;
}
}
}
//if (a3 == (ssl.Count - 1))
{
//SqlCommand ins = new SqlCommand("update sample set N00=" + N00 + " where KeyWord='" + ri + "'", con);
//ins.ExecuteNonQuery();
DataRow[] drSelectAll = ds.Tables[0].Select("KeyWord='" + ri + "'");
drSelectAll[0]["N00"] = N00;
drSelectAll[0]["N01"] = N01;
drSelectAll[0]["N10"] = N10;
drSelectAll[0]["N11"] = N11;
double n = N00 + N11 + N10 + N01;
double w1 = Convert.ToDouble((N11 / n) * (Math.Log(((n * N11) / ((N10 + N11) * (N01 + N11))), 2)));
double w2 = Convert.ToDouble((N01 / n) * (Math.Log(((n * N01) / (((N01 + N00) * (N01 + N11)))), 2)));
double w4 = Convert.ToDouble((N00 / n) * (Math.Log(((n * N00) / (((N00 + N01) * (N00 + N10)))), 2)));
double w3 = Convert.ToDouble((N10 / n) * (Math.Log(((n * N10) / (((N10 + N11) * (N00 + N10)))), 2)));
if (w1.ToString() == "NaN")
{
w1 = 0;
}
if (w2.ToString() == "NaN")
{
w2 = 0;
}
if (w3.ToString() == "NaN")
{
w3 = 0;
}
if (w4.ToString() == "NaN")
{
w4 = 0;
}
double ni = w1 + w2 + w3 + w4;
drSelectAll[0]["MI"] = ni;
ds.Tables[0].Rows.Add(drSelectAll);
}
}
}
try
{
daSelectAll.Update(ds, "sample");
}
catch (Exception)
{
throw;//error
}
Error:Update unable to find TableMapping['sample'] or DataTable 'sample'.
I guess you are missing tablemapping in your code.
Taken from MSDN: "If you do not specify a TableName or a DataTableMapping name when calling the Fill or Update method of the DataAdapter, the DataAdapter will look for a DataTableMapping named "Table". If that DataTableMapping does not exist, the TableName of the DataTable will be "Table". You can specify a default DataTableMapping by creating a DataTableMapping with the name of "Table"."
http://msdn.microsoft.com/en-us/library/ks92fwwh(vs.71).aspx

Categories

Resources