【发布时间】:2017-05-04 15:11:50
【问题描述】:
我有一个网格框,我想在其中填充用户名为 1 的数据库中的数据,并且它们的位置是在过去 24 小时内添加的。
我已经测试了 SQL 查询,它工作正常,但是当尝试将数据放入网格框中时没有任何反应。
这是我在 aspx.cs 文件中使用的代码:
public partial class last24hours : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(@"Data Source = sql2008.net.dcs.hull.ac.uk; Initial Catalog = rde_514872; Integrated Security = True");
protected void Page_Load(object sender, EventArgs e)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Location FROM StaffLocation WHERE [Date and Time]>= getdate()-1 AND [Username] = '1'";
cmd.Connection = con;
DataTable dt = new DataTable();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
gridView1 是我制作的没有 sql 源的空网格视图。
这是在 aspx 文件中初始化 gridview 的方式:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
</asp:GridView>
【问题讨论】:
-
在附加调试器的情况下运行程序,设置断点,并在绑定到 GridView 时检查
dt?它有数据吗?GridView的声明是什么样的? -
我测试了你的代码,它工作得很好。连接不正确或查询未返回任何数据。我怀疑
getdate()-1,这是一个奇怪的结构。最好使用sqlDATEADD。 -
dt 显示的是正确的表格,我也会将我的 aspx 代码用于网格视图,以防出现错误
-
如果您有
AutoGenerateColumns="False"并且您没有在标记中指定列,那么 GridView 将如何显示任何内容?
标签: asp.net sql-server webforms