Displaying multiple entries on a database into an aspx page
我试图将数据库中的多行显示到ASPX页中。我的aspx页面名是news.aspx,我的表名为news。我已经用代码配置了ASPX,以显示我希望页面的外观。我附上了一个图片,显示我希望它看起来像是当页面加载。ASPX页使用itemTemplate&asp:repeater显示多行。
我的ASPX页面配置如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | Latest Sports & Social News Items</asp:label> <ItemTemplate> <p> Title: </asp:Literal> (</asp:Literal>) </p> <p> Title: </asp:Literal> </p> </ItemTemplate> </asp:Repeater> |
我的aspx.cs页面配置为从新闻表中提取信息,我希望在aspx页面中显示三列数据(标题、日期发布和新闻内容)。对于下面的三行,我得到了错误:"名称"…"在当前上下文中不存在。
- little.text=reader["title"].toString();
- litdateported.text=reader["date posted"].toString();
- litNewsContent.text=reader["news content"].toString();
aspx.cx页面配置如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | protected void Page_Load(object sender, EventArgs e) { SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString); string getNewsQuery ="SELECT Id, Title, DataPosted, Newsontent FROM News WHERE Id = @id"; //get email based on id SqlCommand getNewsCommand = new SqlCommand(getNewsQuery, connection); object id = null; getNewsCommand.Parameters.AddWithValue("@id", id); connection.Open(); SqlDataReader reader = getNewsCommand.ExecuteReader(); while (reader.Read()) { litTitle.txt = reader ["Title"].ToString(); litDatePosted.Text = reader["Date Posted"].ToString(); litNewsContent.Text = reader["News Content"].ToString(); } reader.Close(); connection.Close(); } |
我的数据库表配置如下:
1 2 3 4 5 6 7 8 | CREATE TABLE [dbo].[News] ( [Id] INT IDENTITY (1, 1) NOT NULL, [Title] NVARCHAR (100) NOT NULL, [DatePosted] DATE NOT NULL, [NewsContent] NTEXT NOT NULL, [IsRead] BIT DEFAULT ((0)) NULL, PRIMARY KEY CLUSTERED ([Id] ASC)[![enter image description here][1]][1] ); |
有什么想法吗?
尝试如下格式化代码:
1 2 3 | litTitle.txt = reader["Title"].ToString(); litDatePosted.Text = reader["DatePosted"].ToString(); litNewsContent.Text = reader["NewsContent"].ToString(); |
同样,在SQL查询中,您在select语句中输入了一个拼写错误,"newContent"而不是"newContent"
编辑:尝试使用网格视图而不是表格。GridView应根据sqldataadapter提供的SORCE自行格式化。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | protected void Pageaaa_Load(object sender, EventArgs e) { SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString); string getNewsQuery ="SELECT Id, Title, DataPosted, Newsontent FROM News WHERE Id = @id"; //get email based on id SqlCommand getNewsCommand = new SqlCommand(getNewsQuery, connection); object id = null; getNewsCommand.Parameters.AddWithValue("@id", id); connection.Open(); SqlDataReader reader = getNewsCommand.ExecuteReader(); SqlDataAdapter da = new SqlDataAdapter(); DataTable dataTable = new DataTable(); da.Fill(dataTable); GridView1.DataSource = dataTable; GridView1.DataBind(); connection.Close(); da.Dispose(); } |