vs2005中 数据库读取 以及加载列表项的封装函数。

来源:互联网 发布:php购物网站制作 编辑:程序博客网 时间:2024/06/07 15:58

using System.Data.SqlClient;

 

        //输入语句 返回查询结果
        public static SqlDataReader QueryData(string selectStr)
        {
           
            SqlConnection conn = new SqlConnection("Data Source=WSY;Initial Catalog=Mydb;User ID=sa;Password=sss");
            conn.Open();

            SqlCommand cmd = new SqlCommand(selectStr, conn);
            SqlDataReader read = cmd.ExecuteReader();
           
            return read;
        }
    //把SqlDataReader 中的数据加载到ListItem集合

    //用于加载列表选择项 可以支持有ID和无ID的项。

    public static void LoadStrValue(ListItemCollection lic, string Title, SqlDataReader read)
        {
            lic.Clear();
            if (Title != "")
            {
                lic.Add(new ListItem("==" + Title + "=="));
            }
            if (read.FieldCount == 1)
            {
                while (read.Read())
                {
                    lic.Add(new ListItem(read.GetSqlString(0).ToString()));
                }
            }
            else if (read.FieldCount == 2)
            {
                while (read.Read())
                {
                    lic.Add(new ListItem(read.GetSqlString(0).ToString(), read.GetSqlString(1).ToString()));
                }
            }
            read.Close();
           
        }
       

原创粉丝点击