[英]Execute SQL Query on aspx page
Hello fellow programmers, 各位程序员大家好,
I'm really stuck with the simpliest things - i cannot find a way to solve my problem without using mvc. 我真的很坚持简单的事情-如果不使用mvc,我找不到解决问题的方法。
Folder Structure: 资料夹结构:
project
-> App_Data
----> mviedb.mdf
-> Default.aspx
----> Default.aspx.cs
-> Web.config
My mviedb Database so far (table users): 到目前为止,我的mviedb数据库(表用户):
id | user | password
---+--------+------------
1 | daniel | 1
2 | test | test
What I want to do: basically print out what's in my table, so "select * from users" - yet i don't really know how. 我想做的事情:基本上打印出表中的内容,因此“从用户中选择*”-但是我真的不知道如何做。 My Default.aspx.cs file: 我的Default.aspx.cs文件:
namespace mvie {
public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
string query = "select * from users";
if (Query != "") {
try {
SqlDataAdapter adp = new SqlDataAdapter(query, @"data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\mviedb.mdf;User Instance=true");
DataTable dt = new DataTable();
adp.Fill(dt);
} catch (Exception ex) {
}
}
}
}
}
now i need to print the DataTable somewhere. 现在我需要在某个地方打印数据表。 But how? 但是如何? I googled for a while but was not able to find a solution without mvc. 我用谷歌搜索了一会儿,但是没有mvc就找不到解决方案。
As per Steve's comment, ASP.Net WebForms encourages you to use controls such as GridView
or a Repeater
when representing data in tabular fashion. 根据Steve的评论,ASP.Net WebForms鼓励您在以表格形式表示数据时使用GridView
或Repeater
控件。 This will then render the equivalent Html to the browser. 然后,这会将等效的HTML呈现给浏览器。
For example, inside the <form runat="server">
tag in your .aspx
file add the controls: 例如,在.aspx
文件的<form runat="server">
标记内,添加控件:
<asp:DataGrid runat="server" ID="gridUsers"></asp:DataGrid>
<asp:Label runat="server" ID="lblError"></asp:Label>
And in your code behind: 并在后面的代码中:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var query = "select * from users";
try
{
// DataAdapters and DataTables are IDisposable
using (var adp = new SqlDataAdapter(query, @"data source=.\SQLEXPRESS;...;"))
using (var dt = new DataTable())
{
adp.Fill(dt);
// Bind the datatable to the grid
gridUsers.DataSource = dt;
gridUsers.DataBind();
}
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
}
}
Will render a very basic table showing all columns of your users
table. 将呈现一个非常基本的表,显示users
表的所有列。
However, if you can, I would recommend that you leave WebForms (which is a legacy technology) and instead move ahead to ASP.Net MVC, where you will instead fetch the users data in a controller, and render the users table directly in a View. 但是,如果可以的话,我建议您离开WebForms(这是一项旧技术),而继续前进到ASP.Net MVC,在该站点中,您将取回控制器中的用户数据,并直接在视图。 This way you have much finer control over the Html rendering. 这样,您可以更好地控制HTML呈现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.