将表中的列绑定到DropDownList控件


void Page_Load(object sender, System.EventArgs e)
{
  if(!IsPostBack)
  {
    // 创建数据库连接字符串和SQL语句
    string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];
    string query = "SELECT * FROM Products";
    
    // 执行数据库语句并填充数据到 DataTable 中
    SqlCommand myCommand = new SqlCommand(query, new SqlConnection(ConnStr));
    SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
    DataTable dt = new DataTable();
    myAdapter.Fill(dt);
  
    // 数据绑定 DropDownList 控件
    DropDownList1.DataSource = dt;
    DropDownList1.DataTextField = "ProductName";
    DropDownList1.DataValueField = "UnitPrice";
    DropDownList1.DataBind();        
  }
}
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3