简体   繁体   中英

Convert Datetime format to Date from sql and bind to Gridview only date

using (con = new SqlConnection(con_str))
{
    con.Open();
    string sql = "select mcfact as Factory, mcarea as Department, mcloc as Location, mcroom as Room, mcline as Line, cast (scanned as date) from tb_MachineRecord where mcidno='" + cmbmcidno.Text + "' ";
    da = new SqlDataAdapter(sql, con);
    DataSet ds = new DataSet();
    da.Fill(ds);
    GridView7.DataSource = ds;
    GridView7.DataBind();
    con.Close();
}

Using this code the output is with time like 03/05/2016 00:00:00 but when I run this query in SQL it's showing the correct output like 2016-05-03

Instead of ds you can use dt object of datatable for example :

 using (con = new SqlConnection(con_str))
    {
    con.Open();
    string sql = "select mcfact as Factory, mcarea as Department, mcloc as Location, mcroom as Room, mcline as Line, cast (scanned as date) as date from tb_MachineRecord where mcidno='" + cmbmcidno.Text + "' ";
    da = new SqlDataAdapter(sql, con);
    Datatable dt=new datatable();
    da.Fill(dt);

   foreach(DataRow rows in dt.rows.Count)
   {
      rows["date"]=Convert.ToDateTime(rows["date"].toString()).toString("dd/MM/yyyy"));
   }
    GridView7.DataSource = dt;
    GridView7.DataBind();
    con.Close();
   }

If you use BoundFields you can do this

<asp:BoundField DataField="myDBdate" DataFormatString="{0:f}" />

See the Microsoft Site for more BoundField DateTime formats.

If you use TemplateFields you can do this:

<ItemTemplate><%# Convert.ToDateTime(Eval("myDBdate")).ToShortDateString() %></ItemTemplate>

See the Microsoft Site for more DateTime formats

i think you should use

select name,CONVERT(VARCHAR(10),date_of_birth,120) from tbl_Login

date_of_birth is datetime type column

using (con = new SqlConnection(con_str))
{
    con.Open();
    string sql = "select mcfact as Factory, mcarea as Department, mcloc as Location, mcroom as Room, mcline as Line, CONVERT(VARCHAR(10),scanned,120) from tb_MachineRecord where mcidno='" + cmbmcidno.Text + "' ";
    da = new SqlDataAdapter(sql, con);
    DataSet ds = new DataSet();
    da.Fill(ds);
    GridView7.DataSource = ds;
    GridView7.DataBind();
    con.Close();
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM