MySQL get value - c#

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)

Related

SQL Query not Retrieving All Rows in C# Application

I have a stored procedure created in my SQL Server 2012 database that selects data from multiple tables. In C#, I use this procedure to show data in a datagridview.
Issue: when I execute the query in SQL Server, I get the correct result which returns 3 rows, but in C#, it returns only 2 rows.
Query:
SELECT DISTINCT
Employee.Employee_No AS 'Badge'
,Employee.Employee_Name_Ar AS 'Emp Name'
,Employee.Basic_Salary AS 'Basic'
,Employee.Current_Salary AS 'Current'
,Attendance.Present
,Attendance.Leave
,Attendance.Othe_Leave AS 'OL'
,Pay_Slip.Salary_Amount AS 'Sal. Amt.'
,(ISNULL(Pay_Slip.OverTime1_Amount, 0.00) + ISNULL(Pay_Slip.OverTime2_Amount, 0.00)) AS 'O/T Amt.'
,(ISNULL(Pay_Slip.Salary_Amount, 0.00) + ISNULL(ISNULL(Pay_Slip.OverTime1_Amount, 0.00) + ISNULL(Pay_Slip.OverTime2_Amount, 0.00), 0.00)) AS 'Sal. & O/T'
,Pay_Slip.Trasnport AS 'Allow'
,Pay_Slip.CostofLiving AS 'O.Allow'
,Pay_Slip.Gross_Salary AS 'T Salary'
,Pay_Slip.Insurance1_Amount AS 'ss 7%'
,Pay_Slip.Insurance2_Amount AS 'ss 11%'
,(ISNULL(Pay_Slip.Insurance1_Amount, 0.00) + ISNULL(Pay_Slip.Insurance2_Amount, 0.00)) AS 'Total s.s'
,Pay_Slip.Tax
,Pay_Slip.Personal_Loans AS 'Advance'
,Pay_Slip.Other_Deductions AS 'Ded.'
,Pay_Slip.Net_Salary AS 'Net'
FROM Pay_Slip
LEFT JOIN Employee ON Pay_Slip.Employee_No = Employee.Employee_No
LEFT JOIN Attendance ON Pay_Slip.Employee_No = Attendance.Employee_No
WHERE Pay_Slip.Month = '5'
AND Pay_Slip.Year = '2020'
AND Attendance.Month = '5'
AND Attendance.Year = '2020'
Executing this query in SQL Server returns 3 rows which are the employee slips on May-2020 (They all have values in May-2020).
C# code:
private void dateTimePicker_ReportDate_ValueChanged(object sender, EventArgs e)
{
try
{
DateTime date = dateTimePicker_ReportDate.Value;
String Month = dateTimePicker_ReportDate.Value.ToString("MM");
String Year = dateTimePicker_ReportDate.Value.ToString("yyyy");
String str = "server=localhost;database=EasyManagementSystem;User Id=Jaz;Password=Jaz#2020;Integrated Security=True;";
String query = "Execute EMP_PAY_ATT_Selection #Month, #Year";
SqlConnection con = null;
con = new SqlConnection(str);
SqlCommand cmd= new SqlCommand(query, con);
cmd.Parameters.Add("#Month", SqlDbType.Int).Value = Convert.ToInt32(Month);
cmd.Parameters.Add("#Year", SqlDbType.Int).Value = Convert.ToInt32(Year);
SqlDataReader sdr;
con.Open();
sdr = cmd.ExecuteReader();
if (sdr.Read())
{
DataTable dt = new DataTable();
dt.Load(sdr);
dataGridView_Report.DataSource = dt;
dataGridView_Report.EnableHeadersVisualStyles = false;
dataGridView_Report.ColumnHeadersDefaultCellStyle.BackColor = Color.LightBlue;
}
else
{
dataGridView_Report.DataSource = null;
dataGridView_Report.Rows.Clear();
}
con.Close();
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
Again, when running this, it only returns 2 rows on the datagridview. While it should be 3 rows.
These are the tables:
The DbDataReader.Read method advances the reader to the next record.
There is no way to rewind a data reader. Any methods that you pass it to will have to use it from whatever record it is currently on.
If you want to pass the reader to DataTable.Load(), do not Read from it yourself. If you merely want to know if it contains records, use HasRows.

oledb Diffrent mysql columns in one textbox with if command

i'm messing aroung with my new tool i creating at the moment. I got a little problem and dont know how i can get the problem solved. I'm using ole db (accdb file) and a listbox.
So here is my problem:
i've got a quest table
there are a tables named like a_prize_type0 to a_prize_type4 which values are for example 0 (item), 1(gold), 2(exp).
then i got other tables with names like
a_prize_index ( for item ) so if a_prize_type0 = 0
a_prize_data0 (for gold) so if a_prize_type0 = 1
and so on.
No i want to put all these prize values in one textBox and the type in another box.!
So if a_prize_type0 = 0 i want that a_prize_index0 is displayed in box 2 and in box 1 the type is displayed
and if a_prize_type0 = 1 i want that a_prize_data0 is displayed in box 2 and in box 1 the type is displayed
My Code:
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from quest where a_name='" + listBox1.Text + "'";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
textBox28.Text = reader["a_prize_type0"].ToString();
textBox29.Text = reader["a_prize_index0"].ToString();
textBox30.Text = reader["a_prize_data0"].ToString();
textBox31.Text = reader["a_prize_type1"].ToString();
textBox32.Text = reader["a_prize_index1"].ToString();
textBox33.Text = reader["a_prize_data1"].ToString();
textBox34.Text = reader["a_prize_type2"].ToString();
textBox35.Text = reader["a_prize_index2"].ToString();
textBox36.Text = reader["a_prize_data2"].ToString();
textBox37.Text = reader["a_prize_type3"].ToString();
textBox38.Text = reader["a_prize_index3"].ToString();
textBox39.Text = reader["a_prize_data3"].ToString();
textBox40.Text = reader["a_prize_type4"].ToString();
textBox41.Text = reader["a_prize_index4"].ToString();
textBox42.Text = reader["a_prize_data4"].ToString();
textBox64.Text = reader["a_prize_data1"].ToString();
textBox63.Text = reader["a_prize_data2"].ToString();
textBox65.Text = reader["a_prize_data3"].ToString();
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
I hope some understands what i mean >.<
And Thx For that awesome community! And all the people who help me!!
and sry for my bad eng.

Pulling a SELECT query into a datatable and accessing it

I'm writing a small ASP.net C# web page and it keeps giving me an error stating:
There is no row at position 0.
I'm probably doing it wrong but here is some of my code:
string SqlQuery = "SELECT * ";
SqlQuery += " FROM main_list";
SqlQuery += " WHERE ID = #FindID";
SqlConnection conn = new SqlConnection("server=???;database=contacts;User
ID=???;Password=???;");
conn.Open();
SqlCommand SqlCmd = new SqlCommand(SqlQuery, conn);
SqlCmd.Parameters.Add("#FindID",searchID);
SqlDataAdapter da = new SqlDataAdapter(SqlCmd);
try {
da.Fill(dt);
fillData(p);
}
catch {
txtId.Text = "ERROR";
}
And FillData is the following:
protected void fillData(int pos) {
txtId.Text = dt.Rows[pos]["ID"].ToString();
txtCompany.Text = dt.Rows[pos]["Company"].ToString();
txtFirstName.Text = dt.Rows[pos]["First_Name"].ToString();
txtLastName.Text = dt.Rows[pos]["Last_Name"].ToString();
txtAddress1.Text = dt.Rows[pos]["Address1"].ToString();
txtAddress2.Text = dt.Rows[pos]["Address2"].ToString();
txtCity.Text = dt.Rows[pos]["City"].ToString();
txtState.Text = dt.Rows[pos]["State"].ToString();
txtZipCode.Text = dt.Rows[pos]["ZipCode"].ToString();
txtPhoneNum1.Text = dt.Rows[pos]["Phone_Num"].ToString();
txtPhoneNum2.Text = dt.Rows[pos]["Phone_Num2"].ToString();
txtFax.Text = dt.Rows[pos]["Fax_Num"].ToString();
txtEmail.Text = dt.Rows[pos]["Email"].ToString();
txtNotes.Text = dt.Rows[pos]["Notes"].ToString();
txtCategory.Text = dt.Rows[pos]["Category"].ToString();
txtSubCategory.Text = dt.Rows[pos]["SubCategory"].ToString();
txtDateAdded.Text = dt.Rows[pos]["DateAdded"].ToString();
txtDateModified.Text = dt.Rows[0]["DateModified"].ToString();
}
Here is the call that errors out:
protected void btnPrev_Click(object sender, EventArgs e) {
p--;
lblPage.Text = p.ToString();
fillData(p-1);
}
protected void btnNext_Click(object sender, EventArgs e) {
p++;
lblPage.Text = p.ToString();
fillData(p-1);
}
I'm trying to cycle thru the Rows[0] to Rows[1] or however many there is but it gives me the error about no row at position 0 or position 1. It only fills once and then errors out.
EDIT:
I'm trying to access the second row returned by the database after already accessing one row already. For example: Rows[0] is accessible fine but then when I try to read Rows[1] it errors and says it doesn't have a row in position 1. I can revise the code to return Rows[1] and it works but when I try to access Rows[0] it breaks. This is why I pass the variable (p) to fillData so it can show only that Rows value. Thanks!
EDIT 2: I believe it's because there is a postback that wipes the values retrieved by the database. Is there a way to get the database entries to stay even after a postback? If not I am guessing I will have to query the database every time.
The error message indicates there are no rows being returned by SQL. Are you sure there is data to be returned.
When you use dt.Rows[0] you are effectively saying "take the first row that comes back, and get a value from it." If the DataTable doesn't have any rows (i.e. your SQL query returns no matches), that's like saying "Here is a plate that contains no apples. Take the first apple and tell me what colour it is" - see? Doesn't make sense.
What you should do is check whether there are any rows before you try to read them...
if(dt.Rows.Count > 0)
{
// do stuff here.
}
Use Linq and a stored procedure it is much nicer
datacontext context = new datacontext();
var result = context.MyStoredProc(searchID).FirstOrDefault();
Try changing
SqlCmd.Parameters.Add("#FindID",searchID);
to
SqlCmd.Parameters.AddWithValue("#FindID",searchID);
Check your query on your database, make sure rows are actually being returned. Also, it's bad practice to put your query directly into your code like that, especially when using parameters. You might want to try something like this:
private Int32 CallStoredProcedure(Int32 FindId)
{
using (var dt = new DataTable())
{
using (var conn = new SqlConnection(ConnectionString))
{
using (var sqlCmd = new SqlCommand("SEL_StoredProcedure", conn))
{
using (var sda = new SqlDataAdapter(sqlCmd))
{
sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#FindId", FindId);
sqlCmd.Connection.Open();
sda.Fill(dt);
}
}
}
if (dt.Rows.Count == 1)
return Convert.ToInt32(dt.Rows[0]["ID"]);
else if (dt.Rows.Count > 1)
throw new Exception("Multiple records were found with supplied ID; ID = " + studentId.ToString());
}
return 0;
}
To set up your stored procedure, on your database run this:
CREATE procedure [dbo].[SEL_StoredProcedure]
#FindId int = null
as
SELECT * FROM main_list where ID = #FindId
Just remove the index identifier from the code:
e.g.
txtId.Text = dt.Rows["ID"].ToString();

My program seems to be skipping my "If" statement

I have a C# application that submits information to an Access database. I fill in three required boxes , and click "Submit". The script should respond in the following manner when the use clicks the button:
Step 1. Look into database Table A, to see if the value in textBox1 exists in the database.
Step 2. If the value exists, add the values of textBox1, textBox2, and textBox3 into database Table B columns, respectively.
Step 3. If any one of the three text boxes are left blank, display a message.
Step 4. If the value in textBox1 is not in the database table, display a message. (eventually, I plan the replace the message with a default population of the database fields)
THE PROBLEM: When I run the program, in any of the above cases, the result is Step number 4 above. It seems to skip the first "if" statement, and jumping right to the "else" outcome.
Any help resolving this, would be greatly appreciated! The "Private Void "code is below.
Thanks in advance.
private void button1_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand("select * from script_Orders where cust_Name = #UserID", vcon);
OleDbParameter param = new OleDbParameter();
param.ParameterName = "#UserID";
param.Value = textBox1.Text;
cmd.Parameters.Add(param);
OleDbDataReader reader = cmd.ExecuteReader();
{
if (reader.HasRows)
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
{
MessageBox.Show("You must fill in all fields.");
return;
}
else
{
OleDbCommand dbCommand;
OleDbDataReader dbReader;
new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Search\Database.accdb");
dbCommand = new OleDbCommand("select count(*) as Record_Count from script_received", vcon);
dbReader = dbCommand.ExecuteReader();
if (dbReader.Read() == true)
rowCount = dbReader["Record_Count"].ToString();
else
return;
var date = DateTime.Now.ToString("MM/dd/yyyy");
{
using (OleDbCommand command = new OleDbCommand("INSERT INTO script_Received (script, qty, emp_id, received_Date) VALUES (#script,#qty,#emp_Id,#rec_date)"))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#script", OleDbType.Integer).Value = textBox1.Text;
command.Parameters.Add("#qty", OleDbType.VarChar).Value = textBox2.Text;
command.Parameters.Add("#emp_id", OleDbType.VarChar).Value = textBox3.Text;
command.Parameters.Add("#rec_date", OleDbType.Date).Value = date;
command.Connection = vcon;
command.ExecuteNonQuery();
}
this.textBox1.Clear();
this.textBox2.Clear();
this.textBox1.Focus();
}
}
}
else
{
MessageBox.Show("The value of textBox1 is not in the orders table");
return;
}
}
}
If it jumps to the else of if(reader.HasRows) without throwing any exceptions, then reader must not be null, and it's HasRows property must be false. That means your query executed successfully but returned no rows.
You might try running the select statement by hand, which might help you understand what's wrong. Most likely, you're typing something in the textbox that doesn't match any of the cust_name values.

asp.net C# retrieve data from sql according to passed querystring

Assuming that the cardDetailsID is 5.
Looking at record number 5 in the cardDetails table of the database, one can see that its other fields include "bgcolour" and "borderstyle". Therefore, for this particular record I've got cardDetailsID = 5, bgcolour = blue, bordersytle= solid.
I want to be able to get the bgcolour and bordersyle settings (blue and solid) from the cardDetailsID.
This is the code so far. The value in the querystring is working (number "5" is being passed) but now how do I get the rest of the setting of the row?
cardDetailsIDrv.Text = Request.QueryString["cardDetailsID"];
cardDetailsIDrv.Visible = false;
//create Connection
SqlConnection myConnection = new SqlConnection(ConfigurationManager.AppSettings["ConnString"]);
//create Command
SqlCommand getCardDetailsCMD = new SqlCommand("SELECT * FROM cardDetails WHERE cardDetailsID =" + Convert.ToInt32(cardDetailsIDrv.Text), myConnection);
myConnection.Open();
//create datareader
SqlDataReader myReader = getCardDetailsCMD.ExecuteReader();
//code works properly up till here
try
{
//Using DataReader to retrieve info from the database and display it on the panel
while (myReader.Read())
{
//I'm guessing here is where I'm messing things up
pnlCardps.BackColor = Color.FromName(myReader["bgcolour"].ToString());
pnlCardps.BorderStyle = (BorderStyle)Enum.Parse(typeof(BorderStyle), myReader["borderstyle"].ToString());
}
}
finally
{
if (myReader != null)
{
myReader.Close();
}
if (myConnection != null)
{
myConnection.Close();
}
}
PROBLEM SOLVED!!
All I had to do is tweak the code in the while loop to:
string bgColour = myReader["bgColour"].ToString();
pnlCardrv.BackColor = Color.FromName(bgColour);
string borderColour = myReader["borderColour"].ToString();
pnlCardrv.BorderColor = Color.FromName(borderColour);
firstly, you have to get the detailsID which is passed via the query string and then perform the query.
int id;
if(int.TryParse(Request.QueryString["detailsID"],out id))
{
string sql= string.Format("select .. from .. where id={0}",id);// using SqlParameter is much better and secure
// and execute your query and fetch the data reader
while(reader.Read())
{
// bla bla bla
}
}
Request.QueryString["detailsID"] will get you the value of the query string variable.
if (Request.QueryString("detailsID") == null || Request.QueryString("detailsID").Length <= 0 || !int.TryParse(Request.QueryString("detailsID"), out detailsID) || MessageThreadID <= 0)
{
//This is my standard exception, but you can handle it how you want.
throw new Exception("Error: unable to load detailsID. Request.QueryString.count: " + Request.QueryString.Count + " Request.QueryString(\"detailsID\"): " + Request.QueryString("detailsID"));
}

Categories