Combobox items binding in database:
using (MySqlConnection connect = new MySqlConnection(connectionString))
{
string sql = "SELECT DISTINCT tedavi_tarih FROM " + mw.db_name + ".tedavi Where hasta_id= '" + mw.hasta_id + "' ORDER BY tedavi_tarih DESC";
using (MySqlCommand cmd = new MySqlCommand(sql, connect))
{
connect.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
combobox_tarih.Items.Add(reader.GetString("tedavi_tarih"));
}
connect.Close();
}
}
tedavi_tarih format is Date but when I add it to combobox, it displays as "5.01.2018 00:00:00". I want to display only "5.01.2018". I tried this in XAML:
ItemStringFormat="dd/M/yyyy"
It doesn't work. How can I fix it?
reader.GetString("tedavi_tarih") returns a string. It doesn't return a DateTime. A string doesn't become a DateTime when you try to convert it to a string using a DateTime format string.
If the "tedavi_tarih" column really is Date, this should work:
while (reader.Read())
{
combobox_tarih.Items.Add(reader.GetDateTime("tedavi_tarih"));
}
If by "format as Date" you really mean that it's a date formatted as a string, you'll have to use DateTime.TryParse(). Let me know.
Obligatory warning: The code below is a SQL injection vulnerability. It is very bad, very dangerous practice. You should not concatenate SQL strings. You should use SqlParameters instead.
string sql = "SELECT DISTINCT tedavi_tarih FROM " + mw.db_name + ".tedavi Where hasta_id= '"
+ mw.hasta_id + "' ORDER BY tedavi_tarih DESC";
Related
I'm using referenced date-picker control to select date. I get the error
Conversion failed when converting date and/or time from character string
public DataSet comsn(string x, DatePickerControl.DatePicker a, DatePickerControl.DatePicker b)
{
ConnectionStringSettings connectionstringsql = ConfigurationManager.ConnectionStrings["plprojectConnectionString"];
SqlConnection connectionsql = new SqlConnection(connectionstringsql.ConnectionString);
if (connectionsql.State != System.Data.ConnectionState.Open)
{
connectionsql.Open();
}
SqlCommand cmd = new SqlCommand("select a_id,commtyp,comm,primm,c_id,agent from comm where a_id= '" + x + "' AND date>= '" + a.CalendarDate + "' AND date <= '" + b.CalendarDate + "' ", connectionsql);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "comm"); //<------ At this line error occurred [ Conversion failed when converting date and/or time from character string ]
adp.Dispose();
return ds;
}
You can make this work by controlling the date format. When supplied to sql server as a string, I always format my data only string using 'YYYY-MM-DD', i.e., using the ToString('yyyy-MM-dd') on a date field.
However, you are better of turning your query into a parameter driven sql.
i.e., instead of "date >= '" a.Calendardate.ToString("yyyy-MM-dd")
Use "date >= #ADate"
and the supply the parameter value as
cmd.Parameters.Add("ADate", SqlDbType.DateTime).Value = a.Calendardate
I am assuming your datepicker has a "DateTime" property I am treating a.Calendardate as the DateTime property
You can avoid the exception and sql injection by using a parameterized query.
Replace:
SqlCommand cmd = new SqlCommand("select a_id,commtyp,comm,primm,c_id,agent from comm where a_id= '" + x + "' AND date>= '" + a.CalendarDate + "' AND date <= '" + b.CalendarDate + "' ", connectionsql);
With:
string sql = "select a_id,commtyp,comm,primm,c_id,agent from comm where a_id= #x AND date>= #a AND date <= #b "
var cmd = new SqlCommand(sql);
cmd.Parameters.Add("#x", SqlDbType.NVarChar, x);
cmd.Parameters.Add("#a", SqlDbType.DateTime, a);
cmd.Parameters.Add("#b", SqlDbType.DateTime, b);
cmd.Connection = connectionsql;
I've been trying to get this right for over 2hrs so any help is highly appreciated
public void setAppointment(int studentID, DateTime appt)
{
connection.Open();
string sqlStatement3 = "UPDATE dbo.students SET appointmentDate = '" + appt.Date.ToString("yyyy-MM-dd HH:mm:ss") + "' WHERE ID = " + studentID + ";";
OleDbCommand updateCommand = new OleDbCommand(sqlStatement3, connection);
updateCommand.ExecuteNonQuery();
connection.Close();
}
So basically what that does is insert a datetime into an sql server table keeping the same format of the month and day to avoid regional settings getting in the way.
The only problem is that the time remains 00:00:00. Even though when I debug the code, 'appt' shows 28/06/2013 09:30:00
try below
public void setAppointment(int studentID, DateTime appt)
{
connection.Open();
string sqlStatement3 = "UPDATE dbo.students SET appointmentDate = ? WHERE ID = ?";
OleDbCommand updateCommand = new OleDbCommand(sqlStatement3, connection);
updateCommand.Parameters.AddWithValue("#p1", appt);
updateCommand.Parameters.AddWithValue("#p2", studentID);
updateCommand.ExecuteNonQuery();
connection.Close();
}
BUT!
You say it is sql server but why you using OleDbCommand ?
try below if it is sql server
public void setAppointment(int studentID, DateTime appt)
{
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE dbo.students SET appointmentDate = #appointmentDate WHERE ID = #ID";
con.Open();
cmd.Parameters.AddWithValue("#appointmentDate", appt);
cmd.Parameters.AddWithValue("#ID", studentID);
cmd.ExecuteNonQuery();
}
}
Line 5.
Change
... appt.Date.ToString(...
to
... appt.ToString(...
I hope you have solved your problem from previous post and I agree SQL Statements to be used with parameters.
If you have an application date time format is fixed, then there is no harm in hard-coding but it would be good code to get date time format from your web.config file. This will help your code to be same consistent overall project.
Instead of
ToString("yyyy-MM-dd HH:mm:ss")
ToString(ConfigValue)
Too Late, But for your question : Try the code below.
public void setAppointment(int studentID, DateTime appt)
{
connection.Open();
string sqlStatement3 = "UPDATE dbo.students SET appointmentDate = '" + "CONVERT(datetime, '" + appt.Date.ToString("yyyy-MM-dd HH:mm:ss") + "', 103)" + "' WHERE ID = " + studentID + ";";
OleDbCommand updateCommand = new OleDbCommand(sqlStatement3, connection);
updateCommand.ExecuteNonQuery();
connection.Close();
}
I'm experiencing difficulties filtering a set of data between two DateTime values.
For example: Retrieve all records From: 24/04/2013 3:54 PM; To: 24/04/2013 4:30 PM.
I'm programming in C# and using OLE DB to pull data from a Access Database.
The 'To' and 'From' DateTime values are retrieved from DateTimePicker controls on a GUI.
I'm trying to query data in 'receiveDateTime' field of my data source - it is stored in DateTime format in Access.
My code appears as follows:
string SQLQuery = "SELECT EmailID, ServerName, receiveDateTime, Type, status, received, processed"
+ "FROM EmailTable, EmailTypesTable, ServerTable, StatusTable"
+ "WHERE EmailTypesTable.emailTypeID = EmailTypesTable.EmailType "
+ "AND ServerTable.ServerID = EmailTable.serverID "
+ "AND StatusTable.statusID = EmailTable.statusID "
+ "AND EmailTable.receiveDateTime BETWEEN "
+ fromDateTime.Value.ToString("g") + "AND " + toDateTime.Value.ToString("g")";
loadDataGrid(SQLQuery);
Any solutions or advice would be much appreciate.
Thanks,
Allan.
1- It seems you forgot the single quotes between the date values:
string SQLQuery = "SELECT EmailID, ServerName, receiveDateTime, Type, status, received, processed"
+ "FROM EmailTable, EmailTypesTable, ServerTable, StatusTable"
+ "WHERE EmailTypesTable.emailTypeID = EmailTypesTable.EmailType "
+ "AND ServerTable.ServerID = EmailTable.serverID "
+ "AND StatusTable.statusID = EmailTable.statusID "
+ "AND EmailTable.receiveDateTime BETWEEN '"
+ fromDateTime.Value.ToString("g") + "' AND '" + toDateTime.Value.ToString("g") +"' ";
2- It would be better if you use parameterized parameters too:
SqlConnection con = new SqlConnection(MyconnectionString);
con.Open();
string SQLQuery = "SELECT EmailID, ServerName, receiveDateTime, Type, status, received, processed"
+ "FROM EmailTable, EmailTypesTable, ServerTable, StatusTable"
+ "WHERE EmailTypesTable.emailTypeID = EmailTypesTable.EmailType "
+ "AND ServerTable.ServerID = EmailTable.serverID "
+ "AND StatusTable.statusID = EmailTable.statusID "
+ "AND EmailTable.receiveDateTime BETWEEN #dateFrom AND #dateTo";
SqlCommand cmd = new SqlCommand(SQLQuery );
cmd.Parameters.AddWithValue("#dateFrom", fromDateTime.Value.ToString("g"));
cmd.Parameters.AddWithValue("#dateTo", toDateTime.Value.ToString("g"));
SqlDataReader reader = cmd.ExecuteReader();
//...
You could have guessed the issue by trying to execute this query directly in your database
(I have used SQLConnection, SQLCommand... here, you will need to change that part based on the connection you are using.)
For anyone that encounters this problem in future when comparing DateTime value, passing the C# DateTime as an OLE Automation date to the database works!
In order to access this value you use the ToOADate() method.
For example:
SqlConnection con = new SqlConnection(MyconnectionString);
con.Open();
string SQLQuery = "SELECT EmailID, receiveDateTime "
+ "WHERE EmailTable.receiveDateTime "
+ "BETWEEN #dateFrom AND #dateTo";
SqlCommand cmd = new SqlCommand(SQLQuery );
cmd.Parameters.AddWithValue("#dateFrom", fromDateTime.Value.ToOADate());
cmd.Parameters.AddWithValue("#dateTo", toDateTime.Value.ToOADate());
It is quite strange, because although the DateTime values appear in general DateTime Format in the DataGrid, the database must read them as such:
General DateTime Format: 26/04/2013 9:47 AM
OLE Automation Date: 41390.4082198032
Thanks for pointing me in the right direction noobob!
I am Working in ASP.NET and SqlServer.
I have two textboxes with calender extender in my application where user will select two dates.I want to get data between those two dates from sqlserver where my datatype for that particular field is DateTime. please tell me how to proceed with this ...I wrote a query but thats not working..
my query:
SqlCommand cmd = new SqlCommand("select top 1 OrderNumber from tblOrderMaster where OrderedDate>='" + txtfromcal.Text + "' and OrderedDate<='" + txttocal.Text + "' ", conn);
things to do
parameterized the query to prevent from sql injection
use using statement to properly dispose the object
use try-catch block to handle excpetion
eg,
string query = #"select top 1 OrderNumber
from tblOrderMaster
where OrderedDate BETWEEN #startDate AND #endDate";
using(SqlConnection conn = new SqlConnection("connectionString here"))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#startDate", txtfromcal.Text);
cmd.Parameters.AddWithValue("#endDate", txttocal.Text);
try
{
conn.Open();
// other codes
// to fetch the record
}
catch(SqlException e)
{
// do something with
// e.ToString()
}
}
}
SOURCES
AddWithValue Method
Add (recommended method to be used)
use this code:
Sqlcommand cmd=new sql command ("Select data from tablename
where date>=startdate
and date<=enddate",connection)
Try this
SELECT * FROM YourTableName WHERE sqlDateColumnName BETWEEN '" + textbox1.Text + "' AND '" + textbox2.Text + "'
I have a sentence follow:
string strSQL = "update pl_poli set ag_vouch = ' ',ag_vdate = #, ag_vmode = null where
pl_no = '" + textBox5.Text + "' and pl_endtno ='" + textBox6.Text + "'";
I can't update because error "data type mismath". i have fill ag_vdate is type date
I want to Update it -> null
Please can you help me. Thank you so much.
In your case you cannot pass " # " at datetime column because sql server consider this as varchar value and not able to convert this in datetime so...
Try to do as below
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO table1 (column1, column2) VALUES (#param1, #param2)";
command.Parameters.Add("#param1", SqlDbType.DateTime).Value =
DateTime.TryParse(txtDate.Text, out d) ?
(object)d :
DBNull.Value // inserting NULL
...
connection.Open();
command.ExecuteNonQuery();
}