在C#中的GridView中显示最新的10条数据库记录

时间:2018-10-16 11:18:25

标签: c# asp.net database gridview

我想在C#中的GridView中显示最新的10个数据库条目。现在,我正在使用此代码显示从最早到新的条目。

    public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            string constr = ConfigurationManager.ConnectionStrings["jason"].ConnectionString;


            string query = "SELECT TOP 10 did,name,mobile from dealer;";
            query += "SELECT TOP 10 CUSTREGNO,DATEOFCOM,PLANANDTERM from customerreg";

            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        using (DataSet ds = new DataSet())
                        {
                            sda.Fill(ds);
                            gvCustomers.DataSource = ds.Tables[0];
                            gvCustomers.DataBind();
                            gvEmployees.DataSource = ds.Tables[1];
                            gvEmployees.DataBind();
                        }
                    }
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果您有自动递增的主键,我认为这会更容易。然后,您可以从“ SELECT TOP 10 * FROM yourTable ORDER BY YourPrimaryKey DESC”中获取这些值