Retrieving data from OleDb query not displaying in MessageBox - c#

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...

Related

Encountering a System.IndexOutOfRangeException: when trying to display data from two tables in a database

I am writing a form application. User inputs his name, email, address etc into text boxes as if he was ordering a package. If the user has already made an order once I want to make it possible for the user to enter his email into the text box and based on his email fill out all the other personal information needed for the package.
The trouble I am having is that his data is in two different tables. The data which is in customer table (his first and last name) I have successfully retrieved, but the data in the table address I don't know how to get.
Here is the code:
{
try
{
var connection = getConnection();
var command = new SqlCommand
{
Connection = connection,
CommandText = "SELECT * FROM Customer WHERE Email = #Email"
};
command.Parameters.Clear();
command.Parameters.AddWithValue("#Email", mailBox.Text);
connection.Open();
reader = command.ExecuteReader(CommandBehavior.SingleRow);
if (reader.Read())
{
fnameBox.Text = reader["fname"].ToString();
lnameBox.Text = reader["lname"].ToString();
command.CommandText = "SELECT * FROM address WHERE customerID= "+ reader["customerID"].ToString();
stateBox.Text = reader["state"].ToString(); //part where the error happens
cityBox.Text = reader["city"].ToString();
addressBox.Text = reader["address"].ToString();
zipBox.Text = reader["zip"].ToString();
int result = command.ExecuteNonQuery();
connection.Close();
if (result > 0)
{
MessageBox.Show("Success");
}
else
{
MessageBox.Show("Error");
}
}
else
{
MessageBox.Show("E-mail entered doesn't exist");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
} ```
Look into using something like EF in future, will clean such things up, but appreciate this is probably not feasible for what you're doing here.
You should get related data from multiple tables via SQL Joins (look into LEFT JOIN and INNER JOIN)
Your problem is caused by the result set not having a state field, which in turn is caused by your not actually executing your SELECT * FROM address query - you are setting the command text but doing nothing further. You need to create another DataReader for the second query and read those results.
Overall there's a lot of stuff to improve, but you're clearly at an early state in learning this so that's fine for now....
you didn't finish to read the first result and after this trying to get the second one
command.Parameters.Clear();
command.Parameters.AddWithValue("#Email", mailBox.Text);
var customerID=0;
var success=false;
connection.Open();
var reader1 = command.ExecuteReader();
if (reader1.Read())
{
sucess=true;
fnameBox.Text = reader1["fname"].ToString();
lnameBox.Text = reader1["lname"].ToString();
customerID= Convert.ToInt32( reader1["customerID"].ToString());
reader1.Close();
}
if( sucess)
{
command.CommandText = "SELECT * FROM address WHERE customerID = #CustomerID";
command.Parameters.Clear();
command.Parameters.AddWithValue("#CustomerID", customerID);
var reader2 = command.ExecuteReader();
sucess=false;
if (reader2.Read())
{
sucess=true;
stateBox.Text = reader2["state"].ToString();
cityBox.Text = reader2["city"].ToString();
addressBox.Text = reader2["address"].ToString();
zipBox.Text = reader2["zip"].ToString();
reader2.Close();
}
if (success)
{
MessageBox.Show("Success");
}
else
{
MessageBox.Show(" address select Error");
}
}
else
{
MessageBox.Show("E-mail entered doesn't exist");
}
connection.Close();

Mysql read and change variable at the same time

I want to shift some variables by one. I searched for the command for it but I couldn't find. If anybody knows it please help me.
Here is the code:
private int shiftNumbers(int number)
{
int newNumber = 0;
string stm = "UPDATE devices SET number= #newNumber WHERE number>#number";
try
{
con.Open();
cmd = new MySqlCommand(stm, con);
cmd.Parameters.AddWithValue("#number", number);
}
catch (Exception e)
{
ErrorMessage = e.Message;
con.Close();
return null;
}
try
{
rdr = cmd.ExecuteReader();
while(rdr.Read()) {
newNumber = rdr.GetInt32(1);
cmd.Parameters.AddWithValue("#newNumber ", (newNumber-1));
}
}
catch (Exception e)
{
ErrorMessage = e.Message;
con.Close();
return null;
}
con.Close();
return 1;
}
I know this code useless but I show it for you to get the logic that I want to do.
I think your approach is wrong.
First, you read from the database, using a select statement;
Then you go over that result, your rdr.Read();
Then you create a new command, updating the original record;
Move forward in your reader (rdr) and repeat from 2 until you are done.
What you are doing now is impossible. You can't get a result set from an update, just a count affected.
Or, if you can, let your update statement do the calculation (it seems it is only subtracting one from the original number, so why not do that in SQL?):
string stm = "UPDATE devices SET number = number - 1 WHERE number>#number";
Yes, your code is really useless. In your update statement you are passing a parameter #newNumber bu not providing it. Closing the connection in catch block.
string stm = "UPDATE devices SET number= #newNumber WHERE number>#number";
First decide from where you are going to get the #newNumber value and then add that as parameter and use ExecuteNonQuery() method.
If you want pass the other parameter as well in your method and use it like
private int shiftNumbers(int number, int newNumber)
{
//int newNumber = 0;
string stm = "UPDATE devices SET number= #newNumber WHERE number>#number";
using(SqlConnection con = new SqlConnection(connectionString))
{
cmd = new MySqlCommand(stm, con);
SqlParameter paramNumber = new SqlParameter("#number", SqlDbType.Int);
paramNumber.Value = number;
SqlParameter paramNewNumber = new SqlParameter("#newNumber", SqlDbType.Int);
paramNewNumber.Value = newNumber;
cmd.Parameters.Add(paramNumber);
cmd.Parameters.Add(paramNewNumber);
con.Open();
cmd.ExecuteNonQuery();
}
//Rest of your code logic if any
}

How to Display Messagebox When No Values Found on SQL

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

C# data reader does not retrieve the data

I am trying to load data into a textbox by using a DataReader depend on the Drop down list selection. Didn't get error from this code, but the data is not loaded into textbox. please correct me.
public void text()
{
cn1.Open();
string s;
s = "select Request_Type from component where Material_Code='" + Mcodeddl.SelectedItem.Text + "' ";
SqlCommand cd1 = new SqlCommand(s, cn1);
SqlDataReader rd;
try
{
rd = cd1.ExecuteReader();
while (rd.Read())
{
TextBox4.Text = rd["Request_Type"].ToString().Trim();
}
rd.Close();
}
catch (Exception e)
{
Response.Write(e.Message);
}
finally
{
cd1.Dispose();
cn1.Close();
}
}
public void MC()
{
Mcodeddl.Items.Clear();
ListItem li1 = new ListItem();
li1.Text = "-Select-";
Mcodeddl.Items.Add(li1);
Mcodeddl.SelectedIndex = 0;
cn1.Open();
string s1;
s1 = "select Material_Code from component";
SqlCommand cd1 = new SqlCommand(s1, cn1);
SqlDataReader dr1;
try
{
dr1 = cd1.ExecuteReader();
while (dr1.Read())
{
ListItem ni1 = new ListItem();
ni1.Text = dr1["Material_Code"].ToString().Trim();
Mcodeddl.Items.Add(ni1);
}
dr1.Close();
}
catch (Exception e)
{
Response.Write(e.Message);
}
finally
{
cd1.Dispose();
cn1.Close();
}
}
If everything works fine without exceptions that is mean the connection established correctly and the SQL command is correct. I think you have to make sure about your SQL statement. Maybe it returns nothing because there are no matches.
We need more explain about your issue.

assign data from table to labels using c#

I'm using c# in a ASP.Net web application.I have the following query:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from personal,Intrebari where personal.cod_numeric_personal=#cnp AND Intrebari.id_intrebare=14 AND Intrebari.id_intrebare=15 ", con);
cmd.Parameters.AddWithValue("#cnp", Session["sesiune_cnp"]);
SqlDataReader rdr;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
lbl1.Text = rdr["Nume"].ToString();
intrebare6.Text = rdr["Intrebari"].ToString();
intrebare7.Text = rdr["Intrebari"].ToString();
}
I want those two values for id_intrebare=14 and 15 to assign it to those 2 labels.How can i refer to those?
In order to read stuff from the reader you need to include it in the select statement for you sql, it is better to select it explicitly rather than use select *.
but you are not currently going to get any results returned because id_intrebare cannot be both 14 and 15
you then need to read id_intreabare ratherr than Intreabari.
Try this, notice the try catch block, I also changed your SQL query.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
string qry="select * from personal,Intrebari where personal.cod_numeric_personal=#cnp AND Intrebari.id_intrebare IN (14,15);
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#cnp", Session["sesiune_cnp"]);
try
{
con.Open();
SqlDataReader rdr= cmd.ExecuteReader();
if(rdr.HasRows)
{
while (rdr.Read())
{
lbl1.Text = rdr["Nume"].ToString();
intrebare6.Text = rdr["Intrebari"].ToString();
intrebare7.Text = rdr["Intrebari"].ToString();
}
}
}
catch(SQLException ex)
{
lblStatus.Text="An error occured"+ex.Message;
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
If you want to assign texts to different numbered lables in a loop, you can refer to the control id with FindControl of the current page
int numeOrdinal = reader.GetOrdinal("Nume");
int intrebariOrdinal = reader.GetOrdinal("Intrebari");
int i = 1;
while (rdr.Read()) {
// Nume (Romanian) = Name
page.FindControl("lbl" + i).Text = reader.IsDBNull(numeOrdinal)
? ""
: rdr.GetString(numeOrdinal);
// Intrebari (Romanian) = Question
page.FindControl("intrebari" + i + 5).Text = reader.IsDBNull(intrebariOrdinal)
? ""
: rdr.GetString(intrebariOrdinal);
i++;
}
Try using cmd.ExecuteScalar it will return the first reuslt it finds so you have to define your conditions well. Also it returns object type so you will have to cast the result

Categories

Resources