My logic is:
"if selected date is a match with the database date from Holiday
table, return message as "OK"
I have already formatted date in the code shown below. When I do test with hardcoded database date, the code works fine.
How to get database date from my Holiday
table?
PS: Holiday
table includes different dates so system needs to loop and search every row in Holiday
table.
Code:
[System.Web.Services.WebMethod]
public static string GetDateFromDB(DateTime compareDate)
{
string selectedDate = compareDate.ToString("yyyy/MM/dd");
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginDBConnectionString1"].ConnectionString);
SqlCommand com = new SqlCommand("SELECT * from Holiday", conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(com);
DataTable dt = new DataTable();
sqlDa.Fill(dt);
//hardcoded is ok
string dbDateString = "2019-02-20";
DateTime date1 = DateTime.ParseExact(dbDateString.Split(' ')[0], "yyyy/MM/dd", null);
string dateDB = date1.ToString("yyyy/MM/dd");
if (dateDB == selectedDate)
{
return "OK";
}
else
{
return "NG";
}
}
string selectedDate = compareDate.ToString("yyyy/MM/dd");
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginDBConnectionString1"].ConnectionString);
SqlCommand com = new SqlCommand("SELECT * from Holiday where Date='" + selectedDate + "'", conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(com);
DataTable dt = new DataTable();
sqlDa.Fill(dt);
if (dt == null || dt.Rows.Count() == 0)
return "NG";
else
return "OK";
You said you have multi rows so you just can return "OK" or "NG" after loop all row (or break when have error):
[System.Web.Services.WebMethod]
public static string GetDateFromDB(DateTime compareDate)
{
string selectedDate = compareDate.ToString("yyyy/MM/dd");
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginDBConnectionString1"].ConnectionString);
SqlCommand com = new SqlCommand("SELECT * from Holiday", conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(com);
DataTable dt = new DataTable();
sqlDa.Fill(dt);
if (dt != null && dt.Rows.Count > 0)
{
string formatDate = "yyyy/MM/dd";
foreach (DataRow dr in dt.Rows)
{
string dateString = dr["yourColumnName"].ToString();
if (string.IsNullOrEmpty(dateString))
{
continue; // Or set error or something
}
dateString = DateTime.ParseExact(dateString.Split(' ')[0], formatDate, null).ToString(formatDate);
if (dateString.Equals(compareDate))
{
// Do something
}
else
{
// Set error message or something
}
}
// Check after loop and return "OK" or "NG"
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.