WEB

本文介绍如何使用ASP.NET和C#从SQL Server数据库中读取数据,并将其绑定到Web页面上的ListBox和BulletedList控件。通过示例代码展示了如何创建数据库连接、执行SQL查询以及使用数据读取器填充控件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

8.1.3
<%@ Page Language=“C#” AutoEventWireup=“true” CodeFile=“Default.aspx.cs” Inherits="_Default" %>

<form id="form1" runat="server">
    <asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
    <asp:BulletedList ID="BulletedList1" runat="server">
    </asp:BulletedList>
</form>
然后 using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
string connstr = “data source = (localdb)\MSSQLLOCALDB; initial catalog = zln02; integrated security = True”;

protected void Page_Load(object sender, EventArgs e)
{
    using (SqlConnection conn=new SqlConnection(connstr)) {
        SqlCommand cmd = conn.CreateCommand();
        cmd.CommandText = " select Id , name from  [Table] ";
        conn.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        ListBox1.DataSource = reader;
        ListBox1.DataTextField = "Id";
        ListBox1.DataValueField = "name";
        ListBox1.DataBind();
    }
    bindproduct();
}

private void bindproduct()
{
    string ca = ListBox1.SelectedValue;

using(SqlConnection conn=new SqlConnection(connstr))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = “Select name from [Table]”;
cmd.Parameters.AddWithValue("@ca", ca);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
BulletedList1.DataSource = reader;
BulletedList1.DataTextField = “name”;
BulletedList1.DataBind();
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值