How to search with radio Button in c# - 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

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)

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.

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.

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.

Wrong date format C#, Oracle

I'm trying to get my date in the correct format(dd/mm/yyyy). At the moment its in this format: MM-DD-YYYY HH24:MI:SS When I change it to dd/mm/yyyy, it works in the database(Oracle). As soon as I run it in my app I get exception: IndexOutOfRange at :
this.InfoList9.Add(dr["start_rcv_datetime"].ToString());
Please see my code below.
public List<String> InfoList = new List<String>();
private void populatelblDate()
{
conn.Open();
string query;
query = "select to_char(dg.start_rcv_datetime,'dd/mm/yyyy') from dc_pallet dp, dc_pallet_stock dps , dc_grv dg , sku s ,prod_size ps,colour c ,purch_order_carton_sku pocs , dc_crane_instruc dci where dps.pallet_id_no = '" + palletId.ToString() + "' and dp.pallet_id_no = dps.pallet_id_no and dg.dc_grv_id_no = dps.dc_grv_id_no and dg.order_no = dps.order_no and dg.company_id_no = dps.company_id_no and s.company_id_no = dps.company_id_no and s.company_id_no = dg.company_id_no and dps.company_id_no = c.company_id_no and dps.company_id_no = ps.company_id_no and s.prod_size_id_no = ps.prod_size_id_no and s.colour_id_no = c.colour_id_no and dps.company_id_no = ps.company_id_no and pocs.order_no = dps.order_no and pocs.carton_code = dps.carton_code and pocs.company_id_no = dps.company_id_no and pocs.sku_id_no = s.sku_id_no and dci.pallet_id_no(+) = dp.pallet_id_no";
OracleCommand cmd = new OracleCommand(query, conn);
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
this.InfoList.Add(dr["start_rcv_datetime"].ToString());
}
dr.Close();
conn.Close();
}
private void frmInfo_Load(object sender, EventArgs e)
{
populatelblDate();
lbl1.Text = this.InfoList[0];
}
Then I have a prev and next button as well...
Your IndexOutOfRange exception suggests that the immediate problem is that the result set doesn't contain a column of start_rcv_datetime - presumably because of the to_char conversion.
Don't deal with strings at the database side at all. Fetch the value as a DateTime, and then format it at the client in whatever you want to.
Use dr.GetDateTime to fetch the value, having removed the to_char part from your query:
query = "select dg.start_rcv_datetime from ...";
using (OracleCommand cmd = new OracleCommand(query, conn))
{
using (OracleDataReader dr = cmd.ExecuteReader())
{
int dateColumn = dr.GetOrdinal("start_rcv_datetime");
while (dr.Read())
{
DateTime date = dr.GetDateTime(0);
// Or whatever - consider cultural implications
string text = date.ToString("dd/MM/yyyy");
InfoList.Add(text);
}
}
}
(Note the using statements - you should always make sure you clean up your database-related resources.)
Your first column doesn't have a name andso you cannot retrieve it with "start_rcv_datetime"
The immediate solution would be to change the sql to read
query = "select to_char(dg.start_rcv_datetime,'dd/mm/yyyy') as start_rcv_datetime from dc_pallet dp, dc_pallet_stock dps , dc_grv dg , sku s ,prod_size ps,colour c ,purch_order_carton_sku pocs , dc_crane_instruc dci where dps.pallet_id_no = '" + palletId.ToString() + "' and dp.pallet_id_no = dps.pallet_id_no and dg.dc_grv_id_no = dps.dc_grv_id_no and dg.order_no = dps.order_no and dg.company_id_no = dps.company_id_no and s.company_id_no = dps.company_id_no and s.company_id_no = dg.company_id_no and dps.company_id_no = c.company_id_no and dps.company_id_no = ps.company_id_no and s.prod_size_id_no = ps.prod_size_id_no and s.colour_id_no = c.colour_id_no and dps.company_id_no = ps.company_id_no and pocs.order_no = dps.order_no and pocs.carton_code = dps.carton_code and pocs.company_id_no = dps.company_id_no and pocs.sku_id_no = s.sku_id_no and dci.pallet_id_no(+) = dp.pallet_id_no";
However you could simply return the date as a datetime from the database and then use string.Format on the result
eg.
this.InfoList.Add(string.Format("{0:dd/MM/yyyy}", dr["start_rcv_datetime"]));

Categories