Call DateTime argument from Class - c#

I need to call a query between dates
class MemberSched
{
static DataTable GetMemberRecords(DateTime date, DateTime date2)
{
var connSettings = ConfigurationManager.ConnectionStrings["MyDB"];
{
string CN = connSettings.ConnectionString;
MySqlConnection conn = new MySqlConnection(CN);
MySqlCommand cmd = new MySqlCommand("select value 1, value 2, value 3, value 4 from sometable where datefrom >= CAST(#startDate AS DATE) and dateto <= CAST(#endDate AS DATE)", conn);
cmd.Parameters.AddWithValue("#startDate", date);
cmd.Parameters.AddWithValue("#endDate", date2);
MySqlDataAdapter data = new MySqlDataAdapter(cmd);
conn.Open();
DataTable dt = new DataTable();
data.Fill(dt);
return dt;
}
}
}
public object QueryBetweenDate()
{
DataTable table = GetMemberRecords();
return table;
}
private void datePicker_ValueChanged(object sender, EventArgs e)
{
//i don't know what should i put in here
}
private void datePicker2_ValueChanged(object sender, EventArgs e)
{
//i don't know what should i put in here
}
i'm stumped over this, as i'm still new in C#, my query works fine as i have tried it in mysql beforehand, the date arguments on GetMemberRecords i dont know if that is right and also im getting error on public object QueryBetweenDate()

Your SQL is close, but not quite. Try this:
select value 1, value 2, value 3, value 4 from sometable where datefrom BETWEEN #startDate and #endDate
You shouldn't have to cast the datetime variables since the connector will automatically do it as long as you pass in DateTime objects to the parameters. The BETWEEN SQL operator then takes care of making sure it is between the right dates.
Other than the casts, there wasn't anything technically wrong with the original SQL, but BETWEEN is a little easier to understand.

Related

Filter data from sql with datetimepicker as "dd-MM-yyyy" format

I'm trying to filter data from datagirdview by using 2 datetimepicker. Everything goes well when I call a query at SQL server, but when I try to call the same query at c# winform app. I get this error "Conversion failed when converting date and/or time from chracter string."
Here is my sql query for test purposes:
select*from order where CONVERT(datetime, orderDate, 105) between convert(datetime,'01.07.2021',105) and CONVERT(datetime,'15.12.2021',105)
Everything works fine here
Here is my c# filtering code:
private void button23_click(object sender, EventArgs e)
{
try
{
using (SqlConnection con = new SqlConnection(UygulamaAyarlari.ConnectionString()))
{
Datepicker1.Format = DateTimePickerFormat.Custom;
Datepickler1.FormatCustom = "dd-MM-yyyy";
Datepicker2.Format = DateTimePickerFormat.Custom;
Datepicker2.FormatCustom = "dd-MM-yyyy";
MessageBox.Show(bunifuDatepicker1.Value.ToString());
SqlDataAdapter sdf = new SqlDataAdapter("select* from order Where CONVERT(datetime, orderDate, 105) between convert(datetime,'" + bunifuDatepicker1.Value.ToString()+ "',1905) and convert(datetime,'" + bunifuDatepicker2.ToString() + "',1905)", con);
DataTable sd = new DataTable();
sdf.Fill(sd);
DatagridView1.DataSource = sd;
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
Can somebody help me?
Name your controls after you drop them on a form. For you to even have a button handler called button23_Click, implying you have a UI with at least 23 buttons named only numerically, is crazy
Your database orderDate should be a datetime2 column. Let's assume you make it a datetime2(3)
Your code should then look like this:
//button name and click handler name updated
private void GetOrdersCreatedBetweenButton_click(object sender, EventArgs e)
{
try
{
using (SqlConnection con = new SqlConnection(UygulamaAyarlari.ConnectionString()))
{
SqlDataAdapter sdf = new SqlDataAdapter("select * from order Where orderDate between #f and #t", con);
sdf.SelectCommand.Parameters.Add(new SqlParameter("#f", SqlDbType.DateTime2) { Scale = 3, Value = Datepicker1.Value });
sdf.SelectCommand.Parameters.Add(new SqlParameter("#t", SqlDbType.DateTime2) { Scale = 3, Value = Datepicker2.Value });
DataTable sd = new DataTable();
sdf.Fill(sd);
DatagridView1.DataSource = sd;
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
If you make orderDate a datetime, or a datetime2 with a different scale (number of milliseconds precision) adjust the Scale = x in the parameters accordingly

I can't run a correct query on visual studio

I think the problem is in the format.
I have this code in the class:
public DataTable CheckDate(DateTime day)
{
MySqlCommand command = new MySqlCommand("SELECT * FROM `appuntamenti` WHERE `date`='#date'", conn.getConnection());
command.Parameters.Add("#date", MySqlDbType.Date).Value = date;
MySqlDataAdapter adapter = new MySqlDataAdapter();
DataTable table = new DataTable();
adapter.SelectCommand = command;
adapter.Fill(table);
return table;
}
e in the form c#, i use:
private void button2_Click(object sender, EventArgs e)
{
DateTime day = dateTimePicker2.Value;
dataGridView1.DataSource = appuntamento.CheckDate(day);
}
When i click the button2, it is generate the query and the empty filtered table are generated.
The format in database is YYYY-MM-GG but in visual studio the format is GG-MM-YYYY.
I change the format in YYYY-MM-GG but it create an unusual bug (i click on datatimepicker 24/04/2020 but the output datatimepicker is 2020-00-24). When i use my query on localhost/phpmyadmin, it works.
Can you help me?
Try removing the quotes from around #date.
The PDO statement should handle the rest
Remove all quotes in the query.
Like this:
"SELECT * FROM appuntamenti WHERE date = #date"

C# How to reset the Auto Increment ID every 1st date of the Month

I'm having hard time trying to figure out how can i do this. What I'm trying to do is..
For example:
DATE: Oct 1, 2018 to Oct 31, 2018, have 2 records as you can see on the image provided. You can see the id starts at 001 so on and so for. Next month is Nov.. the id should restart/back to 001 not 003.
PS: OrderID is VARCHAR Datatype in my Database
Please note that every new month there is new record displaying so the past record is not seen here
I hope someone would be able to help me
public partial class SIMSSupplier : UserControl
{
ADDPOrders order;
public SIMSSupplier()
{
InitializeComponent();
}
public string ORDERID = "000";
private void ADDOrder_Click(object sender, EventArgs e)
{
order = new ADDPOrders(this);
POrderID._OrderID(order.lbl_orderID);
order.ShowDialog();
}
private void DateOrder_ValueChanged(object sender, EventArgs e)
{
DateBetween._DateOrder(DateOrder, DateOrder, PurchaseOrder);
}
private void DateOrder2_ValueChanged(object sender, EventArgs e)
{
DateBetween._DateOrder(DateOrder, DateOrder2, PurchaseOrder);
}
}
public static class DateBetween
{
public static void _DateOrder(DateTimePicker DateOrder, DateTimePicker DateOrder2, DataGridView PurchaseOrder)
{
using (var con = SQLConnection.GetConnection())
{
using (var select = new SqlCommand("Select * from Purchase_Order where Date between #date1 and #date2", con))
{
select.Parameters.Add("#date1", SqlDbType.Date).Value = DateOrder.Value;
select.Parameters.Add("#date2", SqlDbType.Date).Value = DateOrder2.Value;
using (var sd = new SqlDataAdapter(select))
{
var dt = new DataTable();
sd.Fill(dt);
PurchaseOrder.DataSource = dt;
}
}
}
}
}
If you have the possibility to change the field type to int is much easier to do this from SQL directly. You can auto increment and change the change the seed value each month with a script like the one below (note it also adds the month number in the beginning, if that's useful for you):
IF (DATEPART(DAY, GETDATE()) = 1)
BEGIN
DECLARE #reseedValue INT
SET #reseedValue = CAST(CONCAT(CAST(DATEPART(MONTH, GETDATE()) AS NVARCHAR(4)), '000') AS INT)
DBCC CHECKIDENT ('[table_name]', RESEED, #reseedValue);
END

Getting data from database by getting date from DateTimePicker

I am trying to get data in gridview on the basis of the date that is entered in dateTimePicker. But, I am getting null reference runtime error on if condition where I have used equals function to compare two strings.
ReportFrom.cs
private void button1_Click(object sender, EventArgs e)
{
string date = dateTimePicker.Value.ToShortDateString();
reportLayer.MakeDailyReport(date, dataGridViewReport);
}
ReportLayer.cs
private SqlConnection con = new SqlConnection("Data Source=CHAMP-PC;Initial Catalog=ProcessSale;Integrated Security=True");
private SqlCommand cmd;
private SqlDataAdapter adapt;
public void MakeDailyReport(string givenDate, DataGridView view)
{
try
{
con.Open();
DataTable dt = new DataTable();
cmd = new SqlCommand("SELECT Date FROM FinalSales where Date = #datePicker", con);
cmd.Parameters.AddWithValue("#datePicker", givenDate);
cmd.ExecuteNonQuery();
object dateObject = cmd.ExecuteScalar();
string dateObjectstring = Convert.ToString(dateObject);
string givenDateString = Convert.ToString(givenDate);
// string DBdate = dateObject.ToString();
if (dateObject.Equals(givenDate))
{
adapt = new SqlDataAdapter("SELECT Date FROM FinalSales where Date = " + givenDate + "", con);
if (adapt != null)
{
adapt.Fill(dt);
view.DataSource = dt;
}
else
{
MessageBox.Show("No Record found againts that date");
con.Close();
}
}
else
{
con.Close();
}
}
catch (Exception a)
{
MessageBox.Show(a.Message);
con.Close();
}
}
Have a look here:
Handling ExecuteScalar() when no results are returned
Additionally: Be careful with the call to Equals(). Currently you are comparing
two strings. One with a ShortDate value One with the default ToString().
Event if the dates are equal, this might return false.
A better solution would be handling both values as DateTime and use the == operator.
Thomas

Pulling dateTime from SQL Server database

I'm attempting to compare an endDate column in a SQL Server database to a stored variable called highDate in c#.
DateTime highDate = new DateTime(2999, 1, 1);
SqlConnection myConnection = new SqlConnection("My connection string");
SqlCommand myCommand = new SqlCommand("My query including endDate_TS", myConnection);
myCommand.Connection.Open();
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
DateTime endDate = new DateTime(myReader["endDate_TS"]); //something is wrong here
}
if (endDate > highDate)
{
//do something
}
How do I correctly format the endDate variable I created to accept the endDate_TS from the SQL Server database? (the endDate_TS is a SQL Server DATETIME datatype)
DateTime has several constructors but none which takes an object. But myReader["endDate_TS"] returns an object. If it's actually the number of ticks (what it seems to be if _TS means TimeSpan) you can use the constructor that takes a long:
int indexOfEndDateTsColumn = myReader.GetOrdinal("endDate_TS");
DateTime endDate = new DateTime(myReader.GetInt64(indexOfEndDateTsColumn));
However, the last sentence in parentheses suggests that it's actually a datetime in the database, then you can use DataReader.GetDateTime directly:
DateTime endDate = myReader.GetDateTime(indexOfEndDateTsColumn);

Categories