My datagridview displays date with the year 2015, even if I set my two datetimepickers from two different dates but with the same year (2016).
Heres my code..
public static List<Retailer> GetDataAllRetailer(DateTime past, DateTime present)
{
List<Retailer> data = new List<Retailer>();
MySqlConnection con = DBConnection.ConnectDatabase();
try
{ // AND
MySqlCommand cmd = new MySqlCommand("SELECT * FROM " + tablename + " WHERE (date BETWEEN '" + past.ToString("MM-dd-yyyy") + "' AND '" + present.ToString("MM-dd-yyyy") + "') ", con);
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Retailer rawData = new Retailer();
rawData.Date = reader.GetString(1);
rawData.Walletid = reader.GetString(0);
rawData.Fname = reader.GetString(2);
rawData.Lname = reader.GetString(3);
rawData.Birthdate = reader.GetString(4);
rawData.Address = reader.GetString(5);
rawData.Province = reader.GetString(6);
rawData.City = reader.GetString(7);
rawData.Balance = reader.GetDouble(8);
rawData.Frozen = reader.GetDouble(9);
rawData.Sponsor_id = reader.GetString(10);
rawData.Share = reader.GetDecimal(11);
rawData.Email = reader.GetString(12);
rawData.Password = reader.GetString(13);
rawData.Type = reader.GetInt32(14);
data.Add(rawData);
}
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
return data;
}
}
If the table column is varchar, then I suggest you to convert it to date to do the search appropriately as follows:
SELECT * FROM Table WHERE
CONVERT(DATE, FromDate) >= CONVERT(DATE, '2016-09-03')
AND CONVERT(DATE, ToDate) <= CONVERT(DATE, '2016-09-13')
Related
I want to retrieve all days of a week, selecting any day of that given week.
Example: Wanna retrieve 31/07/2016 (dd/MM/yyyy) to 06/08/2016 (dd/MM/yyyy)
Ocurrences by selecting any day of the presented week.
Is it possible?
My current code:
private void AutoLoadCalendar()
{
string constringF = #"Data Source=|DataDirectory|\cadastramentodb.sdf;Persist Security Info=False";
string QueryF = "select * from Funcionarios where (status = N'Ativo') and datepart(year, datafimcontrato) = #ano and datepart(month, datafimcontrato) = #mes ";
SqlCeConnection conDataBaseF = new SqlCeConnection(constringF);
SqlCeCommand cmdDataBaseF = new SqlCeCommand(QueryF, conDataBaseF);
cmdDataBaseF.Parameters.Add("#mes", SqlDbType.Int).Value = Convert.ToInt32(monthCalendar1.SelectionStart.Month);
cmdDataBaseF.Parameters.Add("#ano", SqlDbType.Int).Value = Convert.ToInt32(monthCalendar1.SelectionStart.Year);
try
{
SqlCeDataAdapter sda = new SqlCeDataAdapter();
sda.SelectCommand = cmdDataBaseF;
System.Data.DataTable dbdatasetF = new System.Data.DataTable();
sda.Fill(dbdatasetF);
BindingSource bSourceF = new BindingSource();
bSourceF.DataSource = dbdatasetF;
dataGridView1.DataSource = bSourceF;
sda.Update(dbdatasetF);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Best regards
You can use the DATEPART function to know witch day of the week has your selected date and knowing that number is easy to solve your problem n___n
Try with this:
private void AutoLoadCalendar()
{
string constringF = #"Data Source=|DataDirectory|\cadastramentodb.sdf;Persist Security Info=False";
string QueryF =
"DECLARE #DiaSemana AS INT " +
"SET #DiaSemana=DATEPART(DW,#Fecha) " +
" " +
"SELECT * " +
"FROM Funcionarios " +
"WHERE [status] = N'Ativo' AND datafimcontrato >= DATEADD(DD,#DiaSemana*-1,#Fecha) AND datafimcontrato <= DATEADD(DD,7-#DiaSemana,#Fecha) ";
SqlCeConnection conDataBaseF = new SqlCeConnection(constringF);
SqlCeCommand cmdDataBaseF = new SqlCeCommand(QueryF, conDataBaseF);
cmdDataBaseF.Parameters.Add("#Fecha", monthCalendar1.Value);
try
{
SqlCeDataAdapter sda = new SqlCeDataAdapter();
sda.SelectCommand = cmdDataBaseF;
System.Data.DataTable dbdatasetF = new System.Data.DataTable();
sda.Fill(dbdatasetF);
BindingSource bSourceF = new BindingSource();
bSourceF.DataSource = dbdatasetF;
dataGridView1.DataSource = bSourceF;
sda.Update(dbdatasetF);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
i have auto generate number create automatically in C#. this sample like this PPP-150500001 , PPP-150500002 => PPP- is a string never change, 15 is a year, 05 is a date, and 00001 is auto generate number.
How Can i reset auto number after get a new year like PPP-160100001 .
this is my method:
public void NomerUrut()
{
long hitung;
string urut;
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = #"SELECT NOPERMOHONAN FROM PERMOHONAN WHERE NOPERMOHONAN IN (SELECT MAX(NOPERMOHONAN)
FROM PERMOHONAN) ORDER BY NOPERMOHONAN DESC";
cmd.Connection = koneksi_manual.con;
koneksi_manual.con.Open(); //open connection
dr = cmd.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
hitung = Convert.ToInt64(dr[0].ToString().Substring(dr["NOPERMOHONAN"].ToString().Length - 5, 5)) + 1;
string joinstr = "00000" + hitung;
DateTime dt = DateTime.Now; // take years and date in autonumber
urut = "PPP-" + dt.ToString("yy") + dt.ToString("MM") + joinstr.Substring(joinstr.Length - 5, 5);
//it will show PPP-150500002, PPP-150500003, etc
//how can i reset this autonumber after get new years like PPP-160100001
}
else
{
urut = "PPP-150500001"; // first form load will display this default autonumber
}
dr.Close();
txtNoPermohonan.Text = urut; //display auto generate number in a textbox
koneksi_manual.con.Close(); //close connection
}
Solved.
i have update for this question and i can finish it using another query to solve my problem. i can reset it every years..
this my update code:
public static string GenerateKodeUrut()
{
string nomor = "";
string date = DateTime.Now.ToString("yyyy/MM/dd").Substring(2, 2);
DateTime dt = DateTime.Now;
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = (#"SELECT NOPERMOHONAN from PERMOHONAN
where substr(NOPERMOHONAN, 5,2) ='" + date + "' ORDER BY cast(substr(NOPERMOHONAN, 9,5) as number) DESC");
cmd.Connection = koneksi_manual.con;
dr = cmd.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
string nmrTerakhir = (dr["NOPERMOHONAN"]).ToString().Remove(0, 8);
nomor = "PPP-" + date + dt.ToString("MM") + (Convert.ToInt32(nmrTerakhir) + 1).ToString("0000#");
}
else
{
nomor = "PPP-" + date + dt.ToString("MM") + "00001";
}
return nomor;
}
you can make a flage in your db to check it && your date.
i hope that code give you my idea
bool flage = false;
int checkdate = Convert.ToInt16(dt.ToString("MM"));
if (checkdate == 12) {
flage = true;
}
if (flage == true && checkdate == 1) {
//Write Your Code Here
flage = false;
}
I Can't do select...
I can not do a select inside a go with dates
recebe uma variavel que determina quantidade de meses a ser calculada MesesDemanda
Calculated a date before and one after
for (int i = 1; i <= MesesDemanda; i++)
{
int cont = 0;
DateTime dataposterior = DateTime.Now, dataanterior = DateTime.Now;
dataanterior = dataanterior.AddMonths(i);
dataposterior = dataposterior.AddMonths(-(i - 1));
con.Open();
cmd = new OleDbCommand("SELECT HistSaida.dataHistSaida, HistSaida.idProdutoHistSaida, HistSaida.qtdHistSaida FROM HistSaida WHERE (((HistSaida.dataHistSaida) BETWEEN #" + dataanterior + "# AND #" + dataposterior + "#) AND idProdutoHistSaida = " + idProduto + ")", con);
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Demanda = Demanda + Convert.ToInt32(dr["qtdHistSaida"]);
cont = 1;
}
}
dr.Close();
con.Close();
Valordivisao = Valordivisao + cont;
}
Use parameters like below
cmd = new OleDbCommand("SELECT dataHistSaida, idProdutoHistSaida, qtdHistSaida FROM HistSaida WHERE ((dataHistSaida <=? AND dataHistSaida >= ?) AND idProdutoHistSaida = ?)", con);
now you can set values like below
cmd.Parameters.AddWithValue("#p1", dataanterior );
cmd.Parameters.AddWithValue("#p2", dataposterior );
cmd.Parameters.AddWithValue("#p3", idProduto );
if you need to take Sum of qtdHistSaida column then you can change the sql statement as below
SELECT SUM(qtdHistSaida) FROM HistSaida WHERE ((dataHistSaida <=? AND dataHistSaida >= ?) AND idProdutoHistSaida = ?)
now you can use ExecuteScalar method to get the sum value as below
var result = cmd.ExecuteScalar();
I have a problem with SqlDataReader.
Here's my code. the problem is when I debug it it doesn't go further than
while(dr.read())
it means the value returned by dr.Read() is false. I don't know what's wrong.
if (CS_time_date[i].Substring(0, 2) == "CS")
{
string cardserial = CS_time_date[i].Substring(4, 5);
try
{
using (SqlConnection con = new SqlConnection(WindowsAppEmp.Properties.Settings.Default.Database1ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from Card_reg ", con);
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
if ((dr["Cardserial"].ToString() == cardserial))
{
flag = 1;
string EmpID = dr["Id"].ToString();
string F_Name = dr["fname"].ToString();
string L_Name = dr["lname"].ToString();
// Insert_EmpReport(EmpID, F_Name, L_Name, cardserial, CS_time_date,con);
string strsql1 = "Insert into Emp_Report (EmpId,CS,fname,lname,CheckIn,CheckOut,Date,Status) values (#EmpID,#Cs,#fname,#lname,#CheckIn,#CheckOut,#Date,#Status)";
SqlCommand report_cmd = new SqlCommand(strsql1, con);
report_cmd.Parameters.AddWithValue("#EmpID", EmpID);
report_cmd.Parameters.AddWithValue("#Cs", cardserial);
report_cmd.Parameters.AddWithValue("#fname", F_Name);
report_cmd.Parameters.AddWithValue("#lname", L_Name);
if (CS_time_date[i].Substring(9, 10) == "56")
if (CS_time_date[i + 2] == DateTime.Now.ToString("dd/mm/yyyy"))
{
report_cmd.Parameters.AddWithValue("#CheckIn", CS_time_date[i + 1]);
report_cmd.Parameters.AddWithValue("#Status", "Present");
}
else
report_cmd.Parameters.AddWithValue("#Status", "Absent");
else
report_cmd.Parameters.AddWithValue("#CheckOut", CS_time_date[i + 1]);
report_cmd.Parameters.AddWithValue("#Date", CS_time_date[i + 2]);
}
else
flag = 0;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
} while (reader.Peek() != -1);
reader.Close();
It looks like you have the Card_reg table defined in your database but this table doesn't contain any values in it - it is empty. That's why the select * from Card_reg query doesn't return any results and the data reader has nothing to read.
I have to search the employee details, which is contained within 3 tables. I have used joins in the query query, but it shows error when I press the search button:
sql command not properly ended
c# coding:
try {
//Search Employee Details
Oracle.DataAccess.Client.OracleConnection cn = new Oracle.DataAccess.Client.OracleConnection();
cn.ConnectionString = "user id=system; password=system;";
Oracle.DataAccess.Client.OracleCommand cmd = new Oracle.DataAccess.Client.OracleCommand();
cmd.Connection = cn;
//cn = new Oracle.DataAccess.Client.OracleConnection();
cmd.CommandText = " select deposit.loanid,
form1.empedoj,
form1.empshare,
sharecapital.shareint,
sharecapital.loandt,
sharecapital.loandeduc,
sharecapital.dividend,
sharecapital.sharetot
from form1,
deposit,
sharecapital
where deposit.loanid(+) = sharecapital.loanid = '" + txtlnid.Text.Trim() + "'"; // shows sql command not properly ended
Oracle.DataAccess.Client.OracleDataAdapter ada = new Oracle.DataAccess.Client.OracleDataAdapter(cmd);
System.Data.DataTable dt = new DataTable();
dt.Clear();
ada.Fill(dt);
//Display in Textbox
if (dt.Rows.Count > 0) {
txtlnid.Text = dt.Rows[0].ItemArray[0].ToString();
admdate.Text = dt.Rows[0].ItemArray[1].ToString();
txtadmamt.Text = dt.Rows[0].ItemArray[2].ToString();
txtadmint.Text = dt.Rows[0].ItemArray[3].ToString();
loandt.Text = dt.Rows[0].ItemArray[4].ToString();
txtlnamt.Text = dt.Rows[0].ItemArray[5].ToString();
txtlnint.Text = dt.Rows[0].ItemArray[6].ToString();
txtsctot.Text = dt.Rows[0].ItemArray[7].ToString();
}
if (cn.State == ConnectionState.Closed) {
cn.Open();
}
string str;
str = cmd.ExecuteScalar().ToString();
if (str != null) {
MessageBox.Show("Record Found");
} else {
MessageBox.Show("ID not Match");
}
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
Your SQL statement becomes
SELECT DEPOSIT.LOANID,
FORM1.EMPEDOJ,
FORM1.EMPSHARE,
SHARECAPITAL.SHAREINT,
SHARECAPITAL.LOANDT,
SHARECAPITAL.LOANDEDUC,
SHARECAPITAL.DIVIDEND,
SHARECAPITAL.SHARETOT
FROM FORM1, DEPOSIT, SHARECAPITAL
WHERE DEPOSIT.LOANID(+) = SHARECAPITAL.LOANID = '" + txtlnid.Text.Trim() + "'";
I suspect it should be:
SELECT DEPOSIT.LOANID,
FORM1.EMPEDOJ,
FORM1.EMPSHARE,
SHARECAPITAL.SHAREINT,
SHARECAPITAL.LOANDT,
SHARECAPITAL.LOANDEDUC,
SHARECAPITAL.DIVIDEND,
SHARECAPITAL.SHARETOT
FROM FORM1, DEPOSIT, SHARECAPITAL
WHERE DEPOSIT.LOANID(+) = SHARECAPITAL.LOANID
AND SHARECAPITAL.LOANID = '" + txtlnid.Text.Trim() + "'";
Also, you have a 3-table join without the correct join conditions, the query is highly likely to return a Cartesian product.
Have you tried putting a semicolon at the end of your query string?
cmd.CommandText = " select deposit.loanid, form1.empedoj, form1.empshare,
sharecapital.shareint, sharecapital.loandt, sharecapital.loandeduc,
sharecapital.dividend, sharecapital.sharetot from form1, deposit ,
sharecapital where deposit.loanid(+) = sharecapital.loanid = '" + txtlnid.Text.Trim() + "';";