So I was trying to add the firstName and lastName in my combobox in my voting system project for our school. I'm getting an error which is getString is not possible to use in this type of syntax. Is there any other way to add this values into 1 single slot to my combo box?
using (MySqlConnection con = new MySqlConnection(connection))
{
//Opening of Connection
con.Open();
MySqlDataReader dataReader;
//FOR PRESIDENT
using (MySqlCommand votePresident = new MySqlCommand(displayPresident, con))
{
try
{
int votePres = 0;
votePres = votePresident.ExecuteNonQuery();
dataReader = votePresident.ExecuteReader();
//Loop to read the Data
while (dataReader.Read())
{
String rollPres = dataReader.GetString("firstName","lastName");
presidentbox.Items.Add(rollPres);
}
}
catch (Exception ex)
{
MessageBox.Show("Failed to Vote" + ex);
}
}
Error Shows this
Problem solved while searching the internet
I used this to connect the 2 strings
while (dataReader.Read())
{
String rollPresf = dataReader.GetString("firstName");
String rollPresl = dataReader.GetString("lastName");
presidentbox.Items.Add(rollPresf + " " + rollPresl);
}
Related
I have an Access database that has name ID-s in a column and I filled up the first column with those ID-s (38, 51, 88) and what I want to do is based on those ID-s I want to fill up the last selected column with some other data that are in the Access database but in another table.
For example, ID 38 would give me a price or a name in that row.
I tried it a lot of times but couldn't find a solution and I don't know If I have to use SQL for this or something else.
I got the needed SQL code but I don't know how to use it for the datagridview.
I have used something like that to fill up combo boxes like this:
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = "the connection string";
connection.Open();
string query2 = "SELECT Name From Names";
command.CommandText = query2;
OleDbDataReader reader2 = command.ExecuteReader();
while (reader2.Read())
{
Combobox1.Items.Add(reader2["Name"].ToString());
}
connection.Close();
And now I think I should make an if statement where it checks if the 38 ID is in the DataGridView, then fill the other cell with the value in the same row of the Access table.
Do you want to populate the datagridview with the corresponding Price and Name that from another table?
Here is a demo you can refer to.
private void btnSetPriceName_Click(object sender, EventArgs e)
{
string constr = #"connection string";
// create sql string
StringBuilder strSQL = new StringBuilder();
strSQL.Append("select Price, Name from PriceName where ");
for(int i = 0;i< dataGridView1.Rows.Count - 1;i++)
{
// get Id from string, like "38/1/R"
string Id = dataGridView1.Rows[i].Cells[0].Value.ToString().Split('/')[0];
if (i == 0)
strSQL.Append("Id = " + Id);
else
strSQL.Append("or Id = " + Id);
}
using (OleDbConnection conn = new OleDbConnection(constr))
{
OleDbCommand cmd = new OleDbCommand (strSQL.ToString(), conn);
conn.Open();
try
{
OleDbDataReader reader = cmd.ExecuteReader();
if (reader != null && reader.HasRows)
{
int rowindex = 0;
while (reader.Read())
{
// Set Price/Name column value
dataGridView1.Rows[rowindex].Cells["Price"].Value = reader[0].ToString().Trim();
dataGridView1.Rows[rowindex].Cells["Name"].Value = reader[1].ToString().Trim();
rowindex++;
}
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine("\nError:\n{0}", ex.Message);
}
}
}
I am getting the output that I do not want to get. I think my code is correct however there might be something I missed.
C# Code:
try
{
string mydbConnection = "datasource=localhost;port=3306;username=root;password=Greenford123;";
MySqlConnection connDB = new MySqlConnection(mydbConnection);
MySqlCommand cmdDataBase = new MySqlCommand("SELECT * FROM project.student", connDB);
MySqlDataReader DBReader;
connDB.Open();
DBReader = cmdDataBase.ExecuteReader();
while (DBReader.Read())
{
List<string> mylist = new List<string>();
mylist.Add(DBReader.ToString());
foreach (var item in mylist)
{
MessageBox.Show("The details are " + item);
}
}
connDB.Close();
}
catch(Exception ex)
{
MessageBox.Show("Error! " + ex);
}
What I want to do is store contents from database into a list so that I could do operations on it. Then I want to output the list however the output is not the "string" or data. The output I get is :
OUTPUT: "the details are MySQL.Data.MySqlClient.MySqlDataReader"
The line:
DBReader = cmdDataBase.ToString();
is wrong. It should be
DBReader = cmdDataBase.ExecuteReader();
If in php we can do something like where $result is some query:
$result = mysql_query("SELECT * FROM student");
if (mysql_num_rows($results) !==0)
{
//do operation.
}
else
echo "no data found in databasae";
What is equivalent to this if I want to do this in C# language?please advise.
I have Created a full Console application using mysql. In your select query you are querying the whole table which is a bad idea. use limit to get only one result - this should be enough to determine if there are any rows in the table.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql;
using MySql.Data.MySqlClient;
namespace ConsoleApplication29
{
class Program
{
static void Main(string[] args)
{
if (AnyRows())
{
Console.WriteLine("There are rows in the database");
}
else
Console.WriteLine("no data found in database");
//This will pause the output so you can view the results. Otherwise you will see the dos screen open then close.
Console.Read();
}
//This is the Methos to call
public static bool AnyRows()
{
string connectionString = "Server=localhost;Database=test;Uid=root;Pwd=yourpassword;";
//Wrap this is using clause so you don't have to call connection close
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string query = "select * from mytable limit 1";
using (MySqlCommand command = new MySqlCommand(query, connection))
{
MySqlDataReader reader = command.ExecuteReader();
return reader.HasRows;
}
}
}
}
}
assuming "results" is of type int
if(results != 0)
{
//do operation
}
else
{
Console.WriteLine("..."); //or output elsewhere
}
c# if else
add a reference to linq, and it gets really easy
var result = SomeDatabaseCall();
if (result.Any()){
// do something
}
if you want to filter the results even further, you can do that inside the Any
var result = SomeDatabaseCall();
if (result.Any(r => r.ID == SomeID)){ // ID can be replaced with any properties in your return model
// do something
}
I got the solution. It is actually very simple. BTW thanks for those who helping. This is the solution:
class DBConnect
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public DBConnect()
{
Initialize();
}
private void Initialize()
{
server = "your_server";
database = "your_db";
uid = "usr";
password = "pwd";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
public void Select()
{
string query = "SELECT * FROM table";
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data in the database
if (dataReader.HasRows == true)
{
while (dataReader.Read())
{
//do retrieve data
}
}else
{
MessageBox.Show("There's no recods in the database");
}
}
}
}
It's best to use SELECT 1 instead of grabbing unnecessary data from the database to simply check for the existence of rows.
public static bool IsTableEmpty(string tableName)
{
string cs = "Server=localhost;Database=test;Uid=root;Pwd=sesame;";
using (var conn = new MySqlConnection(cs))
{
conn.Open();
string sql = string.Format("SELECT 1 FROM {0}", tableName);
using (var cmd = new MySqlCommand(sql, conn))
{
using (var reader = cmd.ExecuteReader())
{
return !reader.HasRows;
}
}
}
}
If you want to get the row count, then you'll need something like:
public static int GetTableRowCount(string tableName)
{
string cs = "Server=localhost;Database=test;Uid=root;Pwd=sesame;";
using (var conn = new MySqlConnection(cs))
{
conn.Open();
string sql = string.Format("SELECT COUNT(*) FROM {0}", tableName);
using (var cmd = new MySqlCommand(sql, conn))
{
return Convert.ToInt32(cmd.ExecuteScalar());
}
}
}
I have a delete button syntax problem in c sharp
and I've made a syntax like this delete button
string conection = "Provider = Microsoft.Jet.OleDb.4.0;Data Source=Database.mdb";
try
{
int i = 0;
for (i = 0; i < dataGridView1.CurrentRow.Cells.Count; i++)
{
DataGridViewCell cell = dataGridView1.CurrentRow.Cells[i];
if (cell.Selected == true)
{
string sql = string.Format("DELETE * FROM mahasiswa WHERE " + i + " ");
OleDbConnection conn = new OleDbConnection(conection);
conn.Open();
dataGridView1.Rows.RemoveAt(i);
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
catch (OleDbException ex)
{
MessageBox.Show(ex.ToString());
}
but the code is syntax error in query, database records do not go to delete
how to code the query syntax is correct?
please help me
I created a database from microsoft access to the names and table names database.mdb supplier with columns id, name, address
primary key: id
Your sql syntax is wrong. It should be something like this:
string sql = string.Format("DELETE FROM mahasiswa WHERE id = {0}", i.ToString());
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...