C# ASP.NET如何将Mysql数据库中的某个字段绑定到DropDownList

79 篇文章 67 订阅

如何使用dropdownlist绑定数据库?我们需要了解dropdownlist的一些属性。

DataSource:为数据源

DataBind:数据源绑定

DataTextField:要显示的文本值

DataValueField:显示文本值的编号

其中DataTextField主要是给用户看的,我们程序员要用的是DataValueField。

一、C#程序添加如下命名空间

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using MySql.Data.MySqlClient;
using System.Data;

二、编写方法,返回DataTable

static string ConnStr = "Server=localhost;UserId=root;Password=12345678;Database=reservoirinfo;pooling=false;CharSet=utf8;port=3306";//声明一个字符串用来存放连接数据库的信息

        public static DataTable Table(string sql)
        {
            using (MySqlConnection conn = new MySqlConnection(ConnStr))
            {
                MySqlDataAdapter sda = new MySqlDataAdapter(sql, conn);
                DataTable dt = new DataTable();
                sda.Fill(dt);
                return dt;
            }
        }

三、数据库reservoirinfo的表名为table1,包含2个字段:id和name

四、DropDownList绑定数据库的id字段和name字段

   id字段提供给程序员,name字段给用户查看选择。

  protected void Page_Load(object sender, EventArgs e)
        {
            string sql = string.Format(" select * from table1");

            DropDownList1.DataSource = Table(sql);
            DropDownList1.DataTextField = "name";
            DropDownList1.DataValueField = "id";
            DropDownList1.DataBind();
        }

 五、前台程序代码

        <asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" style="z-index: 1; left: 287px; top: 95px; position: absolute; height: 22px; width: 235px">
        </asp:DropDownList>

六、运行效果

七、如何获得我选中的那一项的ID值

 int id=int.Parse(this.DropDownList1.SelectedItem.Value);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值