How to Display Messagebox When No Values Found on SQL - c#

Following is a code to get values from table in sql and set it to relevant fields. However i want to know how to write if condition in below block code so if the datatable contains the USERID it will performs function below but if it didn't find the USERID it should popup a error message saying no User Found.
SqlCommand myCommand = new SqlCommand
("SELECT * From USER_TABLE WHERE USERID =" + userIdTextBox.Text, con1);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
nameTextBox.Text = (myReader["FIRST_NAME"].ToString());
lnameTextBox.Text = (myReader["LAST_NAME"].ToString());
posTextBox.Text = (myReader["POSITION"].ToString());
emailTextBox.Text = (myReader["E_MAIL"].ToString());
phoneTextBox.Text = (myReader["PHONE"].ToString());
usernameTextBox.Text = (myReader["USERNAME"].ToString());
userLevelTextBox.Text = (myReader["USER_LEVEL"].ToString());
string filename = (myReader["PROFILE_PICTURE"].ToString());
profilePicBox.Load(filename);
}

You need to check if(myReader.HasRows)
if(MyReader.HasRows)
{
while (myReader.Read())
{
//your code here.
}
}
else
{
// your alert.
}

if (myReader.Read()) //assuming you only ever have a single result...
{
//set form fields.
}
else
{
//message box
}
Edit based on comment from #dmitry-bychenko

Related

How to check if user in mysql database exists (in c#)

So I know this is a often asked question but I want to check if the username is already taken in the database using c#. I tried this:
MySqlCommand cmd2 = new MySqlCommand("SELECT * FROM tablename WHERE(name = '" + tb1.Text + "');");
cmd2.Connection = connect;
connect.Open();
string unt = "";
try
{
MySqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
unt= dr.GetString("name");
}
dr.Close();
}
catch (Exception ex)
{
errorbox.Content = ex.Message;
}
finally
{
connect.Close();
}
if(unt == "" || unt == "0") {
continuel = false;
tb2.Text = "User " +tb1.Text+ " doesn't exist!";
Popup1.IsOpen = true;
}
Its a WPF project and the variable 'continuel' is set to true by default. The code doesn't recognize if a user doesn't exist.
First off your code is vulnerable to sql inject, you should never concatenate values into a query. secondly you can do a count and execute a scalar. Not I stripped down your code a little you'll have to add error handling back.
bool userExists = false;
private String sql = "SELECT COUNT(*) FROM tableName WHERE name = #usernameparam;";
MySqlCommand m = new MySqlCommand(sql);
m.Parameters.AddWithValue("#usernameparam", tb1.Text.Trim());
int userCount = Convert.ToInt32(m.ExecuteScalar());
if(userCount>0)
{
userExists = true;
}
//use userExists variable to evaluate if user exists

How can a test condition be based on the count from query result?

I want to create something like if (reader["assignID"].count > 2) then something happens. But I understand that MySqlDataReader does not have a count function. How else should I approach this?
I want to count the rows.
My code
try
{
string myConnectionString3;
myConnectionString3 = "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
MySqlConnection connection3 = new MySqlConnection(myConnectionString3);
MySqlCommand cmd3 = new MySqlCommand();
EncodingProvider ppp3;
ppp3 = CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(ppp3);
cmd3.CommandType = CommandType.Text;
string sqlStr2 = "Select assignID from assign where userId=#name";
cmd3.Parameters.AddWithValue("#name", txtValue.Text);
cmd3.CommandText = sqlStr2;
cmd3.Connection = connection3;
connection3.Open();
MySqlDataReader reader1 = cmd3.ExecuteReader();
if (reader1.HasRows)
{
while (reader1.Read())
{
if (reader1["assignID"].count > 2) //count rows if more than 2
{
txtAssignID1.Text += "Hello";
}
else
{
btnStart.IsEnabled = true;
string assignID = (reader1["assignID"].ToString());
txtAssignID1.Text += "Your exercise ID is: " + assignID;
}
}
}
else
{
txtAssignID1.Text += "You have not been assigned any exercise ID";
txtAssignID.IsEnabled = false;
}
connection3.Close();
}
catch (MySqlException)
{
}
If you want to know how many assignID for a single user are present then you should ask it to your database. Change your query to
string sqlStr2 = "Select COUNT(assignID) as Totals from assign where userId=#name";
then you use ExecuteScalar to get back the result
int assignCount = 0;
// We need to check for nulls, because if the where condition doesn't
// match any userid then ExecuteScalar returns null.
object result = cmd3.ExecuteScalar();
if(result != null)
assignCount = Convert.ToInt32(result);
And remove all the datareader stuff.
If you need to know also the value of AssignID then you should go back to the MySqlDataReader approach but with a different query again
string sqlStr2 = #"Select assignID, COUNT(assignID) as Totals
from assign where userId=#name
GROUP BY assignID";
.....
MySqlDataReader reader1 = cmd3.ExecuteReader();
if (reader1.HasRows)
{
while (reader1.Read())
{
if ((int)reader1["Totals"] > 2)
{
// Not clear what you want to do if Totals > 2
txtAssignID1.Text += "Hello";
}
else
{
btnStart.IsEnabled = true;
string assignID = (reader1["assignID"].ToString());
txtAssignID1.Text += "Your exercise ID is: " + assignID;
}
}
}
else
{
txtAssignID1.Text += "You have not been assigned any exercise ID";
txtAssignID.IsEnabled = false;
}
If you only need to know if the count is > 2 it may be better to use a count query and execute a GetScalar. This way you only retrieve the data that is necessary.

Show data in Textboxes from database in C#

Is there anything wrong with my code? It is not showing data in textboxes. The same funtion is working for another table in database but not for this one.
private void metroButton1_Click(object sender, EventArgs e)
{
con = new SqlConnection(constr);
String query = "Select FROM Student WHERE Std_ID = '" + metroTextBox1.Text + "'";
cmd = new SqlCommand(query, con);
con.Open();
try
{
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
// metroTextBox1.Text = (read["ID"].ToString());
metroTextBox2.Text = (read["Name"].ToString());
metroTextBox3.Text = (read["F_Name"].ToString());
metroTextBox4.Text = (read["Std_Age"].ToString());
metroTextBox5.Text = (read["Address"].ToString());
metroTextBox6.Text = (read["Program"].ToString());
metroComboBox1.Text = (read["Course"].ToString());
}
}
}
finally
{
con.Close();
}
}
you need to give column names in the select statement or select *
for example :
String query = "Select * from Student WHERE Std_ID = '" + metroTextBox1.Text + "'";
Not related to Question: you can change the while loop to if condition if you have one record for given id. even there are many records for given id you will see the last record data only because of the while loop will overwrite the textboxes in every record.
Update :
There isn't anything wrong with Syntax because the same syntax is
working for modifying teacher funtion.
No, this is incorrect, remove the try catch in your code then you will see the exception of syntax error

How to display items in CheckListBox from ComboBox

I have a comboBox and a checkListBox in my windows form application that connected to my SQL database. I got the binding data part working, but I am not sure how to show the datas in checkListBox when the comboBox item is selected. Let say I have 10 items in my comboBox that bind with my SQL database and they are under the column name ("application name ") such as excel, word, android, eclipse etc.... I call this method when the form begin to load. Sorry for the long code.
Here is my code for that applicationComboBox
private void loadComboBox()
{
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
try
{
myConn.Open();
//my table name is Application_Detail
string query = "select * from Application_Detail";
myCommand = new SqlCommand(query, myConn);
//reading the value from the query
SqlDataReader dr = myCommand.ExecuteReader();
//Reading all the value one by one
while (dr.Read())
{
//column is 1 in Application_Detail Data
//GetString(1) display the 2nd column of the table
string name = dr.GetString(1);
//display the application name in column 2 -
applicationComboBox.Items.Add(name);
}
myConn.Close();
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The outcome of this part of code is:
//label Name //Application Name
Application Name:
Excel
Word
NotePad
PowerPoint
SubLime
Eclipse
After I call this method, I want to display the teacher name that is according to what the user selected in this applicationComboBox. So if teacher 1,2,3 is using Excel and the user selected excel from the comboBox, the checkListBox will display teacher 1,2,3 and vice versa. To do this, I call the method at the comboBox1_SelectedIndexChanged method because I want to display the detail when I select an item from the comboBox. Below is my code
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
//I check if the comboBox index is at 0, it disable the button.
if (applicationComboBox.SelectedIndex == 0)
{
exportButton.Enabled = false;
this.teacherCheckListBox.DataSource = null;
teacherCheckListBox.Items.Clear();
}
//it it is not at 0,
else
{
exportButton.Enabled = true;
//call this method
fill_checkListBox();
}
//teacherCheckListBox
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void fill_checkListBox()
{
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
try
{
myConn.Open();
//for reading purpose, I break down by long statement
//In this statement, I left join 3 table (Teacher_Detail, AppUser_Detail, and Application_Detail table). My AppUser_Detail contains all 3 id (teacherId, applicationId, and AppUserId). I then set filter the table using `where` keyWord to make the applicationId = the comboBox text
string query = "SELECT
td.chineseName,
ad.applicationId,
aud.applicationId,
ad.applicationName
FROM[AppUser_Detail] as aud
LEFT JOIN[Teacher_Detail] as td
ON aud.teacherId = td.teacherId
LEFT JOIN[Application_Detail] as ad
ON aud.applicationId = ad.applicationId
where aud.applicationId = '" + applicationComboBox.Text + "' AND NOT(td.teacherId IS NULL)
";
myCommand = new SqlCommand(query, myConn);
//reading the value from the query
SqlDataReader dr = myCommand.ExecuteReader();
//Reading all the value one by one
while (dr.Read())
{
//column is 0 where the teacherName belong in my Teacher_Detail table
string name = dr.GetString(0);
//I tried to set the text of the checkListBox as the teacherName, but I can't somehow
teacherCheckListBox.Text = name;
}
myConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
When I run the program like this, it said Conversion failed when converting the varchar value "Excel" to data type int. Is there a way to fix it? it shouldn't be a problem because in my Application_Detail table, my applicationName's and my teacherName's data type is set as nvarchar(50) and applicationId and teacherId = int;
The problem is with this line, I would think:
where aud.applicationId = '" + applicationComboBox.Text +
Based on your code, I would think that applicationId is an int and applicationComboBox.Text is just that, text.
Try this:
where ad.applicationName = '" + applicationComboBox.Text.Trim() +
Try this:
if (string.IsNullOrWhiteSpace(teacherCheckListBox.FindString(name))
{
teacherCheckListBox.Items.Add(name);
}

Retrieving data from OleDb query not displaying in MessageBox

I get no exception errors with the below code which could mean there is no problem with my sql statement. However upon trying to verify if it returns any value, i pass the returned items to a string value and try to display it in a message box.
the problem am facing is the message box only displays the name of the column and not the data ive requested from the table.
what could possibly be the problem? and please advice if theres a better way to work around this...
public void DisplayPurchase(OleDbConnection mDB)
{
openDB();
string sqlQuery;
OleDbCommand cmd;
OleDbDataReader rdr;
sqlQuery = "SELECT CustomerTable.[Youth ID], CustomerTable.Firstname, " +
"CustomerTable.Lastname, Youth.Purchaseid, Youth.NumbersOfSport, " +
"Youth.Price, Youth.TotalCostOfTraining, Youth.PercentageDiscount, " +
"Youth.AmountDue, Youth.DatePurchased" +
" FROM CustomerTable, Youth WHERE Youth.YouthID = CustomerTable.[Youth ID]" +
" AND CustomerTable.[Youth ID] = 7";
try
{
cmd = new OleDbCommand(sqlQuery, mDB);
rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
qtyInt1 = (int)rdr["Youth.NumbersOfSport"];
youthInt1 = (int)rdr["CustomerTable.[Youth ID]"];
firstStr1 = (string)rdr["CustomerTable.Firstname"];
purStr1 = (string)rdr["Youth.Purchaseid"];
lastStr1 = (string)rdr["CustomerTable.Lastname"];
priceStr1 = (string)rdr["Youth.Price"];
totalCstStr1 = (string)rdr["Youth.TotalCostOfTraining"];
discountStr1 = (string)rdr["Youth.PercentageDiscount"];
amtDueStr1 = (string)rdr["Youth.AmountDue"];
//purDate1 = (DateTime)rdr["Youth.DatePurchased"];
MessageBox.Show(firstStr1.ToString());
closeDB();
}
else
{
MessageBox.Show("Reader has no rows");
closeDB();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thank you
I'm pretty sure that you have to call rdr.Read() before you can access any data from it. So, add that as the first line after if(rdr.HasRows())
You need to call Read() on the reader to read the first row.
if(rdr.HasRows) {
rdr.Read();
...
Best wishes,
Fabian
Have you tried:
firstStr1 = (string)rdr["Firstname"];
The fieldname in a datareader typically does not include the tablename prefix.
Remove the table names when you are retrieving the data:
qtyInt1 = (int)rdr["NumbersOfSport"];
youthInt1 = (int)rdr["Youth ID"]; // You may need to rename this one in the query
firstStr1 = (string)rdr["Firstname"];
purStr1 = (string)rdr["Purchaseid"];
lastStr1 = (string)rdr["Lastname"];
priceStr1 = (string)rdr["Price"];
totalCstStr1 = (string)rdr["TotalCostOfTraining"];
discountStr1 = (string)rdr["PercentageDiscount"];
amtDueStr1 = (string)rdr["AmountDue"];
Its amazing how this stuff works...
Id firstly like to thank everybody that contributed to solving this problem.Am really grateful for every alphabet posted.
sqlQuery = "SELECT Youth.YouthID, Firstname, Lastname, NumbersOfSport, Price, TotalCostOFTraining, PercentageDiscount, Purchaseid, AmountDue, DatePurchased FROM CustomerTable, Youth WHERE CustomerTable.YouthID = Youth.YouthID AND Youth.YouthID = "+ toSql(youthInt);
try
{
cmd = new OleDbCommand(sqlQuery, mDB);
rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
rdr.Read();
qtyInt1 = (int)rdr["NumbersOfSport"];
youthInt1 = (int)rdr["YouthID"];
firstStr1 = (string)rdr["Firstname"];
purInt1 = (int)rdr["Purchaseid"];
lastStr1 = (string)rdr["Lastname"];
priceStr1 = (string)rdr["Price"];
totalCstStr1 = (string)rdr["TotalCostOfTraining"];
discountStr1 = (string)rdr["PercentageDiscount"];
amtDueStr1 = (string)rdr["AmountDue"];
purDate1 = (DateTime)rdr["DatePurchased"];
closeDB();
}
else
{
MessageBox.Show("Reader has no rows");
closeDB();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I had to call for the rdr.read(); functions as well as taking of the table referencing on the database columns and each help came from a different sources.....
thats awesome...
Thanks everybody...

Categories

Resources