zoukankan      html  css  js  c++  java
  • DropdownList绑定的两种方法

    动态绑定方法一:动态绑定数据库中的字段。

    SqlConnection conn = UtilitySqlClass.OperateDataBase.ReturnConn();
    string strSQL = "select * from CompanyType";
    SqlDataAdapter ada = new SqlDataAdapter(strSQL, conn);
    DataSet ds = new DataSet();
    ada.Fill(ds, "CompanyType");
    DropDownList1.DataSource = ds.Tables["CompanyType"].DefaultView;
    DropDownList1.DataValueField = ds.Tables["CompanyType"].Columns[1].ColumnName;
    DropDownList1.DataTextField = ds.Tables["CompanyType"].Columns[1].ColumnName;
    DropDownList1.DataBind();
    ds.Dispose();

    动态绑定方法二:利用DropDownList.Items.Add方法。

    protected void Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack)
    {
    SqlConnection conn = UtilitySqlClass.OperateDataBase.ReturnConn();
    try
    {
    conn.Open();
    this.DropDownList1.Items.Add("");
    string strSQL = "select CompanyType from CompanyType";
    SqlCommand com = new SqlCommand(strSQL, conn);
    SqlDataReader dr = com.ExecuteReader();
    while (dr.Read())
    {
    this.DropDownList1.Items.Add(dr["CompanyType"].ToString());
    }
    }
    catch (Exception ex)
    {
    Response.Write("<scirpt>alert('" + ex.Message.ToString() + "')</script>");
    }
    finally
    {
    conn.Close();
    }
    }
    }

    第一种方法:
            string ConnString = ConfigurationSettings.AppSettings["ConnectionString"]; 
             //创建一个SqlConnection
             SqlConnection Conn = new SqlConnection( ConnString );        

             string SQL_Select = "select id, ItemName from DDLItem order by id desc";

             //构造一个SqlDataAdapter

             SqlDataAdapter myAdapter = new SqlDataAdapter( SQL_Select, Conn);

             //开始读取数据

             Conn.Open();

             DataSet dataSet = new DataSet();

             myAdapter.Fill( dataSet,"Table1" );

             Conn.Close();

             //开始绑定DropDownList

             //指定DropDownList使用的数据源

             DropDownList1.DataSource = dataSet.Tables["Table1"].DefaultView;

             //指定DropDownList使用的表里的那些字段

             DropDownList1.DataTextField = "ItemName"; //dropdownlist的Text的字段

             DropDownList1.DataValueField = "id";//dropdownlist的Value的字段

             DropDownList1.DataBind();


    第二种方法:
            con.Open();
            SqlCommand cmd = new SqlCommand(strSql,con);
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {      
                DropDownList1.Items.Add(new ListItem(dr["status"].ToString(), dr["status_Id"].ToString()));
            }

  • 相关阅读:
    iOS之地理位置及定位系统 -- 入门笔记(用Swift)
    网易新闻iOS版使用的18个开源组件
    自学 iOS – 三十天三十个 Swift 项目
    iOS之UI--富文本总结
    IOS开发--横向流水布局实现
    IOS开发--仿制网易新闻
    Runtime 方法替换 和 动态添加实例方法 结合使用
    写给IOS开发工程师的网页前端入门笔记
    Runtime(动态添加属性)
    const,static,extern简介(重要)
  • 原文地址:https://www.cnblogs.com/mfryf/p/3105202.html
Copyright © 2011-2022 走看看