绑定到DropDownList,设定Text和value显示

public static void BindDropDownList2(string SqlString, DropDownList MyDDL, string TextStr, string ValueStr)
        {
            SqlDataReader MyReader = GetDataReader(SqlString);

            MyDDL.Items.Clear();
            while (MyReader.Read())
            {
                ListItem MyItem = new ListItem();
                MyItem.Text = MyReader[TextStr].ToString();
                MyItem.Value = MyReader[ValueStr].ToString();
                MyDDL.Items.Add(MyItem);
            }
            MyReader.Close();
        }

 public static SqlDataReader GetDataReader(string SqlString)
        {
            try
            {
                Open();
                SqlCommand cmd = new SqlCommand(SqlString, Connection);
                return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
            }
            catch (System.Data.SqlClient.SqlException ex)
            {               
                throw new Exception(ex.Message);
            }
        }

 

 //定义数据库的打开和关闭方法
        protected static void Open()
        {
            if (Connection == null)
            {
                Connection = new SqlConnection(ConnectionString);
            }
            if (Connection.State.Equals(ConnectionState.Closed))
            {
                Connection.Open();
            }
        }

 

posted @ 2012-12-01 20:29  FiberHomer  阅读(1313)  评论(0编辑  收藏  举报