webform1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="test8_8.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:ListBox ID="ListBox1" runat="server" Height="192px" Width="166px"></asp:ListBox>
</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_8
{
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,"news");
//绑定数据源,设置文本字段,值字段,
ListBox1.DataSource = myDs.Tables["news"];
ListBox1.DataTextField = "title";
ListBox1.DataValueField = "id";
ListBox1.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日上午消息 中国证监会主席在企业投融资论坛上透露,经国务院批准成立创业板。','环球经济','国内新闻');