Wrong date format C#, Oracle - c#

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"]));

Related

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

How To group by date without time sql C#

Hi when i trying to select the date I get also the time, but I need to do group by date without the time.
I also tried this: GROUP BY CAST(Orders.DatePlacing AS DATE), and I tried Convert , DATE(Orders.DatePlacing) and I tried this its not working for me.
Microsoft.ACE.OLEDB.12.0
public Product[] ProfitPrice(DateTime minDate, DateTime maxDate)
{
maxDate=maxDate.AddDays(1);
DataSet ds = new DataSet();
ArrayList products = new ArrayList();
string cmdStr = "SELECT Sum(((Products.PriceSell - Products.Price) * OrdersDetails.ProductCount)) AS Expr1,Orders.DatePlacing FROM Products " +
"INNER JOIN(Orders INNER JOIN OrdersDetails ON Orders.OrderId = OrdersDetails.OrderId) " +
"ON Products.ProductID = OrdersDetails.ProductId WHERE [Orders.DatePlacing] BETWEEN #" + minDate.ToString("yyyy-MM-dd") + "#" + "AND" +
" #" + maxDate.ToString("yyyy-MM-dd") + "# "+
"GROUP BY Orders.DatePlacing";
using (OleDbCommand command = new OleDbCommand(cmdStr))
{
ds = GetMultipleQuery(command);
}
DataTable dt = new DataTable();
try
{
dt = ds.Tables[0];
}
catch { }
foreach (DataRow tProduct in dt.Rows)
{
StatisticsFillArray(tProduct, products);
}
return (Product[])products.ToArray(typeof(Product));
}
private void StatisticsFillArray(DataRow tProduct, ArrayList products)
{
Product productsData = new Product();
productsData.PriceTotal = Convert.ToDouble(tProduct[0].ToString());
productsData.EntryDate = tProduct[1].ToString();
products.Add(productsData);
}
Accordingly to my comment to the question...
your code is sql injection vulnerable!
Do NOT use concatenated string, use parameterized queries instead.
Use table/column aliases!
To reject time part from datetime column, use DateSerial function
How? Take a look at below code:
string sql = #"SELECT Sum(((p.PriceSell - p.Price) * od.ProductCount)) AS Expr1, DateSerial(Year(o.DatePlacing), Month(o.DatePlacing), Day(o.DatePlacing)) DatePlacing
FROM Products p
INNER JOIN(Orders o INNER JOIN OrdersDetails od
ON o.OrderId = od.OrderId)
ON p.ProductID = od.ProductId
WHERE DateSerial(Year(o.DatePlacing), Month(o.DatePlacing), Day(o.DatePlacing)) BETWEEN #mindate AND #maxdate
GROUP BY DateSerial(Year(o.DatePlacing), Month(o.DatePlacing), Day(o.DatePlacing))";
DataTable dt = new DataTable();
using (OleDbConnection oConn = new OleDbConnection(yourConnectionStringHere))
{
oConn.Open();
using (OleDbCommand oComm = new OleDbCommand(yourCommandHere, oConn))
{
oComm.Parameters.Add(new OleDbParameter(){"#mindate", OleDbType = OleDbType.Date, Value = minDate},);
oComm.Parameters.Add(new OleDbParameter(){"#maxdate", OleDbType = OleDbType.Date, Value = maxDate},);
using (OleDbDataReader oRdr = oComm.ExecuteReader())
dt.Load(oRdr);
}
}

how to write a single sql query based on combobox selection?

I have a winform in which user input values through a combobox. I am assigning combobox value to search db. If there is no selection then the SQL server query should not use that column to filter.
example -
if (string.IsNullOrEmpty(combobox1.text)) {
.....Select * from country
}
else if (combobox1.selectedindex > -1) {
....Select * from country where city_name = combobox.text
}
Is there a way to write a single query instead of using this multiple 'IF' conditions in case where user selects or doesn't select a value from combobox.
It is important to parameterize as well:
private const string _select = "select * from country";
void DoSomething()
{
string sql = string.Empty;
if (combobox1.SelectedIndex > -1)
{
command.Parameters.AddWithValue("#1", (string)combobox1.SelectedValue);
sql = " where city_name = #1";
}
sql = _select + sql;
command.CommandText = sql;
command.Execute...
}
#un-lucky asked me how would I deal with many conditions - here is one way
var conditions = new List<string>();
if (/* condition 1*/)
{
command.Parameters.AddWithValue("#2", (string)cboN.SelectedItem);
conditions.Add("col1 = #2");
}
if (/* condition 2*/)
{
command.Parameters.AddWithValue("#3", textBoxN.Text);
conditions.Add("col2 = #3");
}
if (conditions.Count > 0)
sql = _select + " where " + string.Join(" AND ", conditions.ToArray());
You can use the shorthand if only if you have two conditions:
string query = string.Format("Select * from country{0}", string.IsNullOrEmpty(combobox1.text) ? "" : " where city_name = " + combobox1.text);
Hope it helps!
I think you have to try something like this with parameterization:
StringBuilder queryBuilder = new StringBuilder("Select * from country Where 1=1 ");
SqlCommand cmdSql = new SqlCommand();
if (combobox1.selectedindex > -1)
{
queryBuilder.Append(" And city_name = #city_name ");
cmdSql.Parameters.Add("#city_name", SqlDbType.VarChar).Value = combobox.text;
}
else if(Condition 2)
{
queryBuilder.Append(" And column2 = #col2 ");
cmdSql.Parameters.Add("#col2", SqlDbType.VarChar).Value = "some Value here;
}
// Build the query like this
cmdSql.CommandText= = queryBuilder.ToString();
cmdSql.Connection = conObject;
// Here you can execute the command
I have a sample, try it
string select = this.combobox1.GetItemText(this.combobox1.SelectedItem); cm1 = new SqlCommand("Select * from country where city_name=#select or #select is null", con);
cm1.Parameters.Add("#select", SqlDbType.NVarChar, 50);
cm1.Parameters["#select"].Value = select;
dap = new SqlDataAdapter(cm1);
ds = new System.Data.DataSet();
dap.Fill(ds, "DATABASE");
//DataGridView1.DataSource = ds.Tables[0]; get data

Incorrect Syntax near ""

I think my code is correct but why error syntax near 'po_no' check my code please. What is the problem with my code with this kind of error? Do I need to JOIN or two queries? I just want to display the two table using inner join
try
{
if (cb_po_search.Text == "")
{
MessageBox.Show("Please Enter to Search!");
}
else
{
string strPRSconn = ConfigurationManager.ConnectionStrings["POSdb"].ConnectionString;
SqlConnection sc = new SqlConnection(strPRSconn);
sc.Open();
string strQry = "SELECT dbo.POMain.po_no, dbo.POMain.issuing_month, dbo.POMain.supplier, dbo.POMain.model, dbo.POMain.category, dbo.POMain.req_number, dbo.POMain.shipment, dbo.POMain.production_month, dbo.POMain.req_time_arrival, dbo.POMain.req_department, dbo.POMain.lead_time, dbo.POMain.order_desc, dbo.POMain.date_emailed, dbo.POMain.date_confirmed, dbo.POMain.date_recieved, dbo.POMain.assumed_arrival, dbo.Shipping.invoice, dbo.Shipping.loading_date, dbo.Shipping.etd, dbo.Shipping.eta_manila, dbo.Shipping.eta_tstech, dbo.Shipping.ata_tstech, dbo.Shipping.shipping_status, dbo.Shipping.remarks FROM dbo.POMain INNER JOIN dbo.Shipping ON dbo.POMain.po_no = dbo.Shipping.po_noWHERE po_no= '" + cb_po_search.Text + "'";
SqlCommand scmd = new SqlCommand(strQry, sc);
SqlDataAdapter da = new SqlDataAdapter(strQry, sc);
DataTable dt = new DataTable();
SqlDataReader dr = scmd.ExecuteReader();
while (dr.Read())
{
//purchase order
tb_ponumber2.Text = (dr["po_no"].ToString());
tb_reqnumber2.Text = (dr["req_number"].ToString());
cb_supplier2.Text = (dr["supplier"].ToString());
cb_model2.Text = (dr["model"].ToString());
cb_category2.Text = (dr["category"].ToString());
cb_shipment2.Text = (dr["shipment"].ToString());
ta_description2.Text = (dr["order_desc"].ToString());
tb_leadtime2.Text = (dr["lead_time"].ToString());
tb_request2.Text = (dr["req_department"].ToString());
dt_time_arrival2.Value = DateTime.Parse(dr["req_time_arrival"].ToString());
dt_arrival2.Value = DateTime.Parse(dr["assumed_arrival"].ToString());
dt_confirmed2.Value = DateTime.Parse(dr["date_confirmed"].ToString());
dt_email2.Value = DateTime.Parse(dr["date_emailed"].ToString());
dt_production_month2.Value = DateTime.Parse(dr["production_month"].ToString());
dt_recieve2.Value = DateTime.Parse(dr["date_recieved"].ToString());
dt_issuing_month2.Value = DateTime.Parse(dr["issuing_month"].ToString());
}
sc.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Your code is asking for an SQL Injection, use parametized queries instead with SqlParameter class.
Edit. Your query have a missing equals sign at the end. Things that woudn't happen using parametized queries ;-)
http://www.csharp-station.com/Tutorial/AdoDotNet/lesson06

c# integer data load to text box by selecting dropdownlist

i have tried to load the integer value to textbox from db by selecting the dropdownlist item. I didn't get any error, but the value was not display in the text box. this is the code what i have written, please correct me,
public void SiteNo()
{
Conhr.Open();
//int anInteger;
//anInteger = Convert.ToInt32(TextBox1.Text);
//anInteger = int.Parse(TextBox1.Text);
string sq = "select SiteCode from tbl_SiteMaster where Sitealiasname='" + ddlsite.SelectedItem.Text + "' ";
SqlCommand d = new SqlCommand(sq, Conhr);
SqlDataReader r;
r = d.ExecuteReader();
while (r.Read())
{
TextBox1.Text = r.GetValue(0).ToString();
}
r.close();
Conhr.Close();
}
//change code to this to find the problem
public void SiteNo()
{
Conhr.Open();
//int anInteger;
//anInteger = Convert.ToInt32(TextBox1.Text);
//anInteger = int.Parse(TextBox1.Text);
string sq = "select count(SiteCode) from tbl_SiteMaster where Sitealiasname='" + ddlsite.SelectedItem.Text + "' ";
SqlCommand d = new SqlCommand(sq, Conhr);
SqlDataReader r;
r = d.ExecuteReader();
while (r.Read())
{
TextBox1.Text = r.GetValue(0).ToString();
}
r.close();
Conhr.Close();
}

Categories