【发布时间】:2016-12-12 12:46:53
【问题描述】:
我正在使用 Visual Studio 在 C# 中创建一个 asp.net Web 应用程序。我有一个注册页面,孩子们可以在其中注册,然后他们的详细信息被发送到我数据库中的“孩子”表中,点击“查看已注册的孩子”按钮后,会打开一个新页面,其中显示名字、出生日期和用户名( pk) 的每个注册儿童。按照目前的情况,DOB 被存储并读取为“04/02/2006”。我现在需要找到一种从 DOB 获取年龄并能够按年龄组(6-10、11-13、14-16)查看孩子的方法。
我想知道实现这一目标的最简单方法是什么?每个年龄组的单选按钮,即在选择时,只显示GridView中该年龄组中的孩子。或者当页面被加载并且所有的孩子都显示在网格视图上时,他们已经被分类到年龄组中?
请记住,我是 C# 和 asp.net 的新手,谁能告诉我实现这一目标的最简单方法!我附上了我的 gridview 当前外观的屏幕截图。提前致谢。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace Coursework
{
public partial class Testy1 : System.Web.UI.Page
{
//create a datasource
SqlDataSource source = new SqlDataSource();
protected void Page_Load(object sender, EventArgs e)
{
//always set some defaults for the sqldatasource
source.ID = "source1";
SqlConnection connectionString = new SqlConnection(ConfigurationManager.ConnectionStrings["newregDBConnectionString"].ConnectionString);
source.SelectCommand = "SELECT firstname, dob, DATEDIFF(hour, dob, GETDATE()) / 8766 AS age FROM table ORDER BY age";
if (!IsPostBack)
{
//bind the grid
GridView1.DataSource = source;
GridView1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//the new database query, now with where clause
source.SelectCommand = "SELECT firstname, dob, DATEDIFF(hour, dob, GETDATE()) / 8766 AS age FROM table WHERE (DATEDIFF(hour, dob, GETDATE()) / 8766 BETWEEN @start AND @end) ORDER BY age";
//get the end age from the dropdown and cast as int
int end = Convert.ToInt32(DropDownList1.SelectedValue);
//get the start int for the filter
int start = end - 5;
//if the filter is resetted, make sure the query returns all ages
if (end == 0)
{
start = 0;
end = 99;
}
//replace the parameters in the query
source.SelectParameters.Add("start", start.ToString());
source.SelectParameters.Add("end", end.ToString());
//rebind the grid
GridView1.DataSource = source;
GridView1.DataBind();
}
}
}
【问题讨论】:
-
对网格的数据源进行排序。
-
您能详细说明一下吗?我以前从未使用过gridviews,对.net 和c# 完全陌生!
-
如何将数据放入 GridView ?你bind it to the
DataSource?还是你手动做的 -
所以你应该让你的 dob 列可点击,点击时你点击(去)到你的控制器,具体属性 sortByDate ="ASC" 或 sortByDate="Desc" 取决于你的情况。当您在您的索引控制器中,并且您收到此参数 sortByDate 时,您应该使用 .OrderByDescending 或 OrderBy 这个日期查询数据。如果您使用的是 mvc。如果您使用的是 asp.net 表单,方法是相同的,但您需要在单击按钮时使用正确排序的数据重新绑定 DataGrid。
-
我已将其绑定到数据源。我会尝试这种方法,不过我使用的是 asp.net 表单,那么如何在单击按钮时使用正确排序的数据重新绑定数据网格?