webform1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="test8_5.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataGrid ID="DataGrid1" runat="server"></asp:DataGrid>
</div>
</form>
</body>
</html>
webform1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace test8_5
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//数据库连接字符串
string connectionString = @"Data Source=LAPTOP-AQKEN65V\SQLEXPRESS08;Initial Catalog=db_news;User ID=sa;Password=123456;";
//新建连接,打开连接
SqlConnection myConnection = new SqlConnection(connectionString);
myConnection.Open();
//查询sql,新建适配器
string selectSql = "select id,title from tb_news";
SqlDataAdapter adapter = new SqlDataAdapter(selectSql, myConnection);
//新建数据集
System.Data.DataSet myDs = new System.Data.DataSet();
adapter.Fill(myDs);
//绑定数据源
DataGrid1.DataSource = myDs;
DataGrid1.DataBind();
//关闭连接
myConnection.Close();
}
}
}
}
sql
CREATE DATABASE db_news
USE db_news
GO
CREATE TABLE dbo.tb_news(
id int identity(1,1) not null primary key,
title varchar(50) not null,
content varchar(2000) not null,
categories varchar(50) not null,
type1 varchar(50) not null,
issueDate datetime not null default getdate())
GO
insert into tb_news(title,content,categories,type1)
values('创业板开板','新浪财经讯10月17日上午消息 中国证监会主席在企业投融资论坛上透露,经国务院批准成立创业板。','环球经济','国内新闻');