Unable to get records from database when date format is dd/MM/yyyy in ASP.Net

Last Reply on Sep 01, 2014 06:32 AM By Azim

Posted on Sep 01, 2014 03:49 AM

i put it in page i refresh the page but i never got the output

using System.Configuration;
using System.Data.SqlClient;
using System.Globalization;



protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT message FROM tblMessages WHERE CONVERT(VARCHAR(10),DisplayDate,21) = @DisplayDate", con))
            {
                cmd.Parameters.AddWithValue("@DisplayDate", DateTime.Now.ToString("yyyy-MM-dd", new CultureInfo("en-gb")));
                con.Open();
                object message = cmd.ExecuteScalar();
                con.Close();
                if (message != null)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + message.ToString() + "')", true);
                }
            }
        }
    }
}

 

Posted on Sep 01, 2014 06:32 AM Modified on on Sep 08, 2014 07:55 AM

You need to use CultureInfo for converting the MM/dd/yyy format.

HTML

<asp:TextBox ID="txtOrderDate" Text="05/07/1996" runat="server" />`
<asp:Button Text="Search Name With Order Date" OnClick="SearchNameWithOrderDate"
    runat="server" />

Namespaces

using System.Configuration;
using System.Data.SqlClient;
using System.Globalization;

C#

protected void SearchNameWithOrderDate(object sender, EventArgs e)
{
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT FirstName FROM Employees employees INNER JOIN  Orders orders ON employees.EmployeeId = orders.EmployeeId   WHERE OrderDate = @OrderDate", con))
        {
            cmd.Parameters.AddWithValue("@OrderDate", Convert.ToDateTime(this.txtOrderDate.Text.ToString(),new CultureInfo("en-GB")));
            con.Open();
            object name = cmd.ExecuteScalar();
            con.Close();
            if (name != null)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + name.ToString() + "')", true);
            }
        }
    }
}