else if (listBox1.SelectedIndex == 1)
{
String sql2 = "SELECT FirstName, LastName FROM Players WHERE Team = 'Milwaukee Bucks'" +
"AND Number < 24";
// command statement
command = new SqlCommand(sql2, cnn);
SqlDataReader reader = command.ExecuteReader();
// Get table values
if (reader.Read())
{
textBox1.Text = reader.GetString(0).ToString() + " " + reader.GetString(1).ToString();
}
cnn.Close();
command.Dispose();
}
Above is a section of my code. I have a list box with options for the user to choose, and based on which item is selected, a display button will run a query and return the results to a textbox.
However, when I run the code I am only getting one result back. The query returns players on the Bucks who have a number less than 24. There should be multiple of them but I am only getting one in my C# application.
You need to use a while loop to read all the lines instead of reading a single line (via Read()).
Microsoft Documentation has an example of how to use the while loop.
StringBuilder sb = new StringBuilder()
while (reader.Read())
{
sb.AppendLine(reader.GetString(0).ToString() + " " + reader.GetString(1).ToString());
}
textBox1.Text = sb.ToString();
Related
Since yesterday I am trying to get this value (see image), I have tried to use "mysqlreader, executescalar and more", but I cannot get the number of lines.
What I want to do is this:
If the result is 0 it does nothing, if equal to 1 it must show an image, if greater than 1 it must show another image
ex code 1
private void patient()
{
if (OpenEventMissionData.Rows.Count != 0)
{
foreach (DataGridViewRow row in OpenEventMissionData.Rows)
{
string idevent = row.Cells[1].Value.ToString();
string sql = "SELECT COUNT(*) FROM patient INNER JOIN event WHERE patient.ID_EVENT = " + "'" + idevent + "'" + "AND evento.EVENT_OPEN = 1;";
MySqlConnection connection = new MySqlConnection();
connection.ConnectionString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
MySqlCommand cmd = new MySqlCommand(sql, connection);
connection.Open();
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
DataGridViewButtonColumn patient = new DataGridViewButtonColumn();
OpenEventMissionData.Columns.Add(new PatientColumn());
}
}
}
}
I tried adding the code that told me #oldDog, but the result is always 6
ex code 3
NEW EDIT:
In fact 6 lines appear.
phpmyadmin
Your problem here is you are using HasRows. Since you are doing SELECT COUNT(*) you will always have one row which will contain the count, even if the count is zero. Instead you could use:
if (Convert.ToInt32(reader[0]) > 0)
fees_structure has 24 "A" Category rows. But when I try to fetch them and print, it only displays 20 or (21 rows sometimes)
Here is my code:
string catA = "SELECT id,fees_name,amount,fee_category FROM fees_structure where fee_category='A' ORDER BY id";
using (SqlCommand scom = new SqlCommand(catA, con))
{
using (SqlDataReader read = scom.ExecuteReader())
{
read.Read();
if (read.HasRows)
{
while (read.Read())
{
feestableA.Append("<tr>");
feestableA.Append("<td>" + read["fees_name"] + "</td>");
feestableA.Append("<td>" + read["amount"] + "</td>");
feestableA.Append("</tr>");
}
plcfeesA.Controls.Add(new Literal { Text = feestableA.ToString() });
plcfeesA.Dispose();
}
}
}
The read() before the while is suspicious. I suspect that is eating one row.
Another possibility for losing rows would be case-sensitive collations -- if the category could be 'a' (or a variant in another encoding). However, this depends on the default or explicit collations used for the column, database, and server.
I dont think this is a C# issue.
Try this
string catA = "SELECT id,fees_name,amount,fee_category FROM fees_structure where fee_category like '%A%' ORDER BY id";
Just see if your results change
Try this. Watch closely, I removed lines of code that were doing stuff you did not want to be done.
string catA = "SELECT id,fees_name,amount,fee_category FROM fees_structure where fee_category='A' ORDER BY id";
using (SqlCommand scom = new SqlCommand(catA, con))
{
using (SqlDataReader read = scom.ExecuteReader())
{
while (read.Read())
{
feestableA.Append("<tr>");
feestableA.Append("<td>" + read["fees_name"] + "</td>");
feestableA.Append("<td>" + read["amount"] + "</td>");
feestableA.Append("</tr>");
}
plcfeesA.Controls.Add(new Literal { Text = feestableA.ToString() });
}
}
}
I have two dropdownlists one of the country (worlddrdolist) and the another is of states (staatddl) and the button (NumOfUsrBtn) where if the user since click on it then the label will show the total sum of users depending on a country selected from (worlddrdolist) First whatever if the user select the state or not also if the user select the state then it will show the users depending of the country , the below code need update and fix some of part as i tried my best to fix but i coundnt, and i am receiving error message:
"Must declare the scalar variable "#cou"." also "Must declare the
scalar variable "#sta"."
protected void NumOfUsrBtn_Click(object sender, EventArgs e)
{
using (var conn = new SqlConnection(sc))
{
string UsrNumSQL = "SELECT COUNT (UsrID)FROM UserInfo WHERE 1=1 AND Country = #cou AND State=#sta";
using (var cmd = new SqlCommand(UsrNumSQL, conn))
{
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 10000;
cmd.Parameters.AddWithValue("#cou", worlddrdolist.SelectedValue);
cmd.Parameters.AddWithValue("#sta", staatddl.SelectedValue);
string condition = "";
if (worlddrdolist.SelectedValue != "")
{
condition += " and Country='" + worlddrdolist.SelectedValue + "'";
}
if (staatddl.SelectedValue != "")
{
condition += " and State='" + staatddl.SelectedValue + "'";
}
cmd.Connection.Open();
NumbOfUsersLbl.Text = cmd.ExecuteScalar().ToString();
}
}
}
This is not how parameterized queries works.
You need add your parameter value as a parameter in your command, not an additional condition.
cmd.Parameters.AddwithValue("#cou", worlddrdolist.SelectedValue);
cmd.Parameters.AddwithValue("#sta", staatddl.SelectedValue);
But I strongly suspect you just wanna add additional conditions with AND... at first place, you don't need to use parameter in your command at all. Looks like your conditions is not known at compile time, instead you wanna build them in runtime.
In such a case, just delete unnecessary parts in your query since you wanna add them based on your condition like;
string UsrNumSQL = "SELECT COUNT (UsrID)FROM UserInfo WHERE 1=1";
...
...
if (worlddrdolist.SelectedValue != "")
{
condition += " and Country='" + worlddrdolist.SelectedValue + "'";
}
if (staatddl.SelectedValue != "")
{
condition += " and State='" + staatddl.SelectedValue + "'";
}
cmd.Connection.Open();
NumbOfUsersLbl.Text = cmd.ExecuteScalar().ToString();
I am struggling here trying to understand (after a lot of research a futzing with this) why my MySQL query in C# is returning only one row and the values are wrong.
public static void loadCombinedPaymentExportData(Int32 iFromId = 0)
{
// VERIFIED STATE OF CONNECTION (OUTPUTS "OPEN")
Console.Write(oConn.State+"\n");
// TRIED USING PREPARED STATEMENTS FIRST
//OdbcCommand oCommand = new OdbcCommand("SELECT * FROM v_payment_export_combined_rec WHERE id > ? LIMIT 10", oConn);
//oCommand.Parameters.Add("#ID", OdbcType.Int).Value = iFromId;
// ENDED UP TRYING A MORE DIRECT APPROACH SO I COULD SEE WHAT IS HAPPENING
string sQuery = "SELECT * FROM v_payment_export_combined_rec WHERE id > " + iFromId.ToString() + " LIMIT 10";
// OUTPUTS "SELECT * FROM v_payment_export_combined_rec WHERE id > 0 LIMIT 10"
Console.WriteLine(sQuery);
OdbcCommand oCommand = new OdbcCommand(sQuery, oConn);
using (OdbcDataReader oReader = oCommand.ExecuteReader())
{
// THIS ENTERS INTO THE BLOCK AS HAVING ROWS
if (oReader.HasRows)
{
while (oReader.Read())
{
// THIS ONLY OUTPUTS ONCE AS "Data: 1"
Console.WriteLine("\nData: {0}", oReader.GetString(0));
}
}
else
{
Console.WriteLine("No rows found.\n");
}
oReader.Close();
oCommand.Dispose();
}
}
The issue here is if I run the same exact query on the database using my SQL editor, I have something like 190k+ rows come back from the view, and the lowest id is 8. In fact, I tried adding additional output like:
Console.WriteLine("\nData: {0} | {1} | {2}", oReader.GetString(0), oReader.GetString(1), oReader.GetString(2));
And every single one of them comes back as a 1, which is incorrect as the 2nd column has real text.
Curiously, I had previously done a similar test on another table using this same logic and it worked just fine.
What am I messing up?
[EDIT]
Just tried using the MySQL .NET Connector instead of ODBC and got the same result.
string sQuery = "SELECT * FROM v_payment_export_combined_rec WHERE id > " + iFromId.ToString() + " LIMIT 10;";
MySqlCommand oCommand = new MySqlCommand(sQuery, oConn);
using (MySqlDataReader oReader = oCommand.ExecuteReader())
{
if (oReader.HasRows)
{
while (oReader.Read())
{
Console.WriteLine("\nData: {0}", oReader.GetString(0));
}
}
else
{
Console.WriteLine("No rows found.\n");
}
oReader.Close();
oCommand.Dispose();
}
I will keep investigating here to see if I can figure out what is going on.
I have a database that stores invoice information. Each invoice can have up to 5 jobs relation, each job has a unique id number.
I've performed a select statement selecting all jobs relevant to a single invoice.
I have tried many ways to read the selected job id and store them in a jobArray. I would prefer to have it selecting using a for loop but most of the ways I've tried use textBoxes (which I replaced with my array)
This is my most recent code;
SqlCeCommand cmdCountJobs = new SqlCeCommand("SELECT COUNT(Job_ID)AS INVCOUNT FROM Invoice WHERE Invoice_Number = " + maxInvoice + " ", cn);
cmdCountJobs.Connection = cn;
reader = cmdCountJobs.ExecuteReader();
while (reader.Read())
{
countValue = Convert.ToInt32(reader["INVCOUNT"].ToString());
}
SqlCeCommand cmdJobSearch = new SqlCeCommand("SELECT Job_ID as ID FROM Invoice WHERE Invoice_Number = " + maxInvoice + " ", cn);
cmdJobSearch.Connection = cn;
reader = cmdJobSearch.ExecuteReader();
SqlCeDataAdapter da = new SqlCeDataAdapter(cmdJobSearch);
jobArray[0] = (reader.Read()) ? reader["ID"].ToString() : "";
jobArray[1] = (reader.Read()) ? reader["ID"].ToString() : "";
jobArray[2] = (reader.Read()) ? reader["ID"].ToString() : "";
jobArray[3] = (reader.Read()) ? reader["ID"].ToString() : "";
jobArray[4] = (reader.Read()) ? reader["ID"].ToString() : "";
}
Could you help me with this?
Why use an array? You could use a List(Of Int) to store the ID numbers using a normal loop.
And given the nature of lists you don't need to know before hand the number of jobs to set your array size, so you could have an Invoice with only 4 jobs or one with 6, but the logic of your code will not need to check for this.
List<int> jobs = new List<int>();
SqlCeCommand cmdJobSearch = new SqlCeCommand("SELECT Job_ID as ID FROM Invoice " +
"WHERE Invoice_Number = #ivc", cn);
cmdJobSearch.Connection = cn;
cmdJobSearch.Parameters.AddWithValue("#ivc", maxInvoice);
reader = cmdJobSearch.ExecuteReader();
while(reader.Read())
jobs.Add(Convert.ToInt32(reader["ID"]));
Also note that I have changed your query to avoid string concatenation. Probably this is not the case but it is a good practice to use parametrized queries to avoid Sql Injection
Of course, if you have the need to use an array somewhere in the remainder of your code, you can easily reference the list like an array
TextBox1.Text = jobs[0].ToString();
or convert the list back to an array with
int[] ids = jobs.ToArray();