oledb Diffrent mysql columns in one textbox with if command - c#

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.

Related

MySQL get value

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)

How to search with radio Button in c#

Table Form
I'm trying to filter this table with RadioButton when DateDePublication is Checked and the value of the search text equals for example 2000 table should return all books who have DateDePublication equals to 2000
this is Search Button code :
private void RechBtn_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = repository.GetAllLivres(rechtext.Text);
}
and search method code to return all books :
public List<Livre> FilterDateDePublication(string date)
{
using (var connection = factory.CreateConnection())
{
var livres = new List<Livre>();
connection.ConnectionString = connectionString;
connection.Open();
var command = factory.CreateCommand();
command.Connection = connection;
command.CommandText = "select * from livre where date_publication like '%" + date + "%'";
using (DbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Livre l = new Livre();
l.Isbn = reader["isbn"].ToString();
l.Titre = reader["titre"].ToString();
l.DatePublication = DateTime.Parse(reader["date_publication"].ToString());
l.NombrePage = Int32.Parse(reader["nombre_page"].ToString());
l.Couverture = reader["couverture"].ToString();
l.Prix = Double.Parse(reader["nombre_page"].ToString());
l.QuantiteDisponible = Int32.Parse(reader["quantite_disponible"].ToString());
}
}
return livres;
}
your function GetAllLivres just looks for books with a specifc string in their title.
command.CommandText = "select * from livre where titre like '%" + mc + "%'";
You should change that to search on the pub date. Can says how that should look because we dont know your database scheme.
By the way , do not build SQL like that, its a huge security hole. Use parametrized queries
I know i have 4 radio buttons when one of them is checked Search function should look up by each of radio button.
Well again not seeing the UI its hard to say but my guess is you have something like this
|-search by: --------| <<< group box
| ( ) Author | << radio buttons
| ( ) title |
| (*) Year |
----------------------
Search for :_________________: <<== text box
[Start Search] <<== button
I hope so.
So do this
if(radioYear.Checked){
FilterDateDePublication(searchText.Text);
}
else if(radioAuthor.Checked)
.......
Note that the date the user enters might not match the format of the date in the database, in that case you need to do some massaging
I would however refactor your code, you have surely noticed that 90% of your FilterDateDePublication is the same as the title one.
You should do
public List<Livre> ReadBooks(string query)
{
using (var connection = factory.CreateConnection())
{
var livres = new List<Livre>();
connection.ConnectionString = connectionString;
connection.Open();
var command = factory.CreateCommand();
command.Connection = connection;
command.CommandText = query;
using (DbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Livre l = new Livre();
l.Isbn = reader["isbn"].ToString();
l.Titre = reader["titre"].ToString();
l.DatePublication = DateTime.Parse(reader["date_publication"].ToString());
l.NombrePage = Int32.Parse(reader["nombre_page"].ToString());
l.Couverture = reader["couverture"].ToString();
l.Prix = Double.Parse(reader["nombre_page"].ToString());
l.QuantiteDisponible = Int32.Parse(reader["quantite_disponible"].ToString());
}
}
return livres;
}
and then have
List<Livre> GetByDate(string date){
return GetBooks("select * from livre where date_publication like '%" + date + "%'";
}
even better would be to use sql parameters. I will update this answer later

hi i want to view an output on a chart but there's no ouput when i clicked the button here's the code

hi i am using c# and i want to view an output on a chart but there's no output when i clicked the button here's the code:
try
{
Connection();
sql_connect.Open();
string s = "select count(*) from tbl_order where grand_total > " + textBox1.Text;
sql_command = new MySqlCommand(s, sql_connect);
sql_command.ExecuteNonQuery();
chart1.Series["Fast"].Points.AddXY("Product1", s);
string sc = "select count(*) from tbl_order where grand_total < " + textBox2.Text;
sql_command = new MySqlCommand(s, sql_connect);
sql_command.ExecuteNonQuery();
chart1.Series["Slow"].Points.AddXY("Product2", sc);
}
catch(Exception o)
{
MessageBox.Show(o.Message);
}
At the moment you don't read any data from the database. I'll just assume that your SQL connection is already set up correctly - probably that's what the Connection Method is doing? Then you just do:
try
{
var sqlCommand = new SqlCommand($"SELECT count(*) AS number FROM tbl_order WHERE grand_total > {textBox1.Text}", sql_connect);
var reader = sqlCommand.ExecuteReader();
while(reader.Read())
chart1.Series["Fast"].Points.AddXY("Product 1", (int) reader["number"]);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
It's the same for the second table. If you want to know more about reveiving data from a database, take a look at this: https://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C.

Problems with displaying data in datagrid view column

I am using datagrid view in a windows form application. I have several data grids that display a date date column. When I display my data, the date shows correctly but is always followed by '00:00:00'. How can I change it to only display the date as 'dd/mm'yyyy'.
I build my datagrid as follows:
//Populate customers datagrid view
private void displayInGrid_Customers(string sqlcmd)
{
customersDataGridView.Rows.Clear();
connect.Open();
command.Connection = connect;
command.CommandText = sqlcmd;
reader = command.ExecuteReader();
while (reader.Read())
{
// add a row ( get index )
int arow = customersDataGridView.Rows.Add();
// datagridname.row[index].cells.value = reader[table].tostring()
customersDataGridView.Rows[arow].Cells[0].Value = reader["Customer_ID"].ToString();
customersDataGridView.Rows[arow].Cells[1].Value = reader["Forename"].ToString();
customersDataGridView.Rows[arow].Cells[2].Value = reader["Surname"].ToString();
customersDataGridView.Rows[arow].Cells[3].Value = reader["Address"].ToString();
customersDataGridView.Rows[arow].Cells[4].Value = reader["Town"].ToString();
customersDataGridView.Rows[arow].Cells[5].Value = reader["Postcode"].ToString();
customersDataGridView.Rows[arow].Cells[6].Value = reader["Date_Of_Birth"].ToString();
customersDataGridView.Rows[arow].Cells[7].Value = reader["Phone_Number"].ToString();
customersDataGridView.Rows[arow].Cells[8].Value = reader["Email"].ToString();
customersDataGridView.Rows[arow].Cells[9].Value = reader["Current_Rental"].ToString();
customersDataGridView.Sort(Surname, ListSortDirection.Ascending);
}
reader.Close();
connect.Close();
}
//Display all customers button
private void button_view_all_customers_Click(object sender, EventArgs e)
{
command.CommandText = "SELECT CUSTOMERS.Customer_ID, CUSTOMERS.Forename, CUSTOMERS.Surname, CUSTOMERS.Address, "
+ "CUSTOMERS.Town, CUSTOMERS.Postcode, CUSTOMERS.Date_Of_Birth, CUSTOMERS.Phone_Number, CUSTOMERS.Email, CUSTOMERS.Current_Rental "
+ "from CUSTOMERS LEFT JOIN STOCK ON CUSTOMERS.Current_Rental = STOCK.Product_ID";
string cmd = command.CommandText;
displayInGrid_Customers(cmd);
Also, I have another problem in a different datagrid. This one has a payment column and when I originally created the table in access, the data in the column was like '£4.99' and right justified as expected but when I display it, there is no '£' symbol and it is left justified.
Code for that datagrid is:
//Populate payments datagrid view
private void displayInGrid_Payments(string sqlcmd)
{
paymentsDataGridView.Rows.Clear();
connect.Open();
command.Connection = connect;
command.CommandText = sqlcmd;
reader = command.ExecuteReader();
while (reader.Read())
{
// add a row ( get index )
int arow = paymentsDataGridView.Rows.Add();
paymentsDataGridView.Rows[arow].Cells[0].Value = reader["Customer_ID"].ToString();
paymentsDataGridView.Rows[arow].Cells[1].Value = reader["Payment"].ToString();
paymentsDataGridView.Rows[arow].Cells[2].Value = reader["Payment_Date"].ToString();
}
reader.Close();
connect.Close();
}
//Display all payments
private void button_display_payments_Click(object sender, EventArgs e)
{
command.CommandText = "SELECT PAYMENTS.Customer_ID, PAYMENTS.Payment, PAYMENTS.Payment_Date "
+ "from PAYMENTS LEFT JOIN CUSTOMERS ON PAYMENTS.Customer_ID = CUSTOMERS.Customer_ID";
string cmd = command.CommandText;
displayInGrid_Payments(cmd);
}
For the first part try:
customersDataGridView.Rows[arow].Cells[6].Value = ((DateTime)reader["Date_Of_Birth"]).ToShortDateString()
And for the second part try:
paymentsDataGridView.Rows[arow].Cells[1].Value = reader["Payment"].ToString("C");
paymentsDataGridView.Rows[arow].Cells[1].Value = String.Format("{0:C}", decimal.Parse(reader["Payment"].ToString()));
If it still gives error, try changing decimal for double, although for money and currency I would avoid double because of rounding errors it could give.

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