Adil Yar
Adil Yar

Reputation: 45

how to get date in dd/MM/yyyy format from textbox?

I'm getting data between two date from query but problem is textbox getting data in YYYY/MM/dd format i need to convert it into dd/MM/yyyy.

Start Date: <asp:TextBox ID="txtstart" runat="server" TextMode="Date" ></asp:TextBox>
End Date: <asp:TextBox ID="txtend" runat="server" TextMode="Date"></asp:TextBox>
<p>
  <asp:Button ID="btnfetch" runat="server" Text="Button" OnClick="btnfetch_Click1" />
</p>
<div>
  <asp:GridView ID="GridView2" runat="server">
  </asp:GridView>
</div>
using (SqlCommand cmd = new SqlCommand(
  "SELECT Name,Present from AttendanceRecords " + 
  "where Date between '" + txtstart.Text + "' and '" + txtend.Text + "' ", con))
{
    con.Open();   
    SqlDataAdapter da = new SqlDataAdapter(cmd);

    DataTable dt = new DataTable();
    da.Fill(dt);
    SqlDataReader rdr = cmd.ExecuteReader();
    if (rdr.Read())
    {
        GridView2.DataSource = dt;
        GridView2.DataBind();
    }
    else
    {
        lbldatercrd.Text = "NOT FOUND";
    }

Upvotes: 0

Views: 1860

Answers (1)

Cetin Basoz
Cetin Basoz

Reputation: 23797

Adil,

  • You should always use parameters to prevent SQL injection attack,
  • It is expected that you should use a DateTime or DatePicker, TimePicker controls instead of textboxes but for the time being I would assume you are getting valid dates in the format of yyyy/MM/dd.
  • You shouldn't use BETWEEN for datetime range queries IF there is a possibility that the values would also have time portions. But here looks like you are only dealing with dates so that might be OK.

A DataAdapter opens and closes the connection as needed.

DateTime start, end;
if (DateTime.TryParse(txtStart.Text, out start) && DateTime.TryParse(txtEnd.Text, out end))
{
  string cmd = @"SELECT Name,Present 
      from AttendanceRecords   
      where [Date] between @start and @end";

  SqlDataAdapter da = new SqlDataAdapter(cmd, con);
  da.SelectCommand.Parameters.Add("@start", SqlDbType.DateTime).Value = start;
  da.SelectCommand.Parameters.Add("@end", SqlDbType.DateTime).Value = end;

  DataTable dt = new DataTable();
  da.Fill(dt);
  GridView2.DataSource = dt;
  GridView2.DataBind();
}
else
{
    lbldatercrd.Text = "NOT FOUND";
}

Upvotes: 1

Related Questions