【WPF学习笔记】之如何设置下拉框读取SqlServer数据库的值:动画系列之(一)

先前条件:设置好数据库,需要三个文件CommandInfo.cs、DbHelperSQL.cs、myHelper.cs,需要修改命名空间,参照之前随笔http://www.cnblogs.com/Owen-ET/p/5999654.html

添加一个表的类User_test对应数据库的表,如下图:

User_test类:

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;


namespace User.sqlHelper
{
    [Serializable]
    class User_test
    {
        public User_test()
        {

        }

        #region
        private int _userID;
        private string _userName;
        private int _userGrade;
        private string _userPassword;

        public int UserID
        {
            set { _userID = value; }
            get { return _userID;  }
        }

        public string UserName
        {
            set { _userName = value;}
            get { return _userName; }
        }

        public int UserGrade
        {
            set { _userGrade = value; }
            get { return _userGrade;  }
        }

        public string UserPassword
        {
            set { _userPassword = value;}
            get { return _userPassword; }
        }

        #endregion

        #region

        public User_test(int userID)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select UserID,UserName,UserGrade");
            strSql.Append(" FROM [User] ");
            strSql.Append(" where UserID=@userID");

            SqlParameter[] parameter = { 
                    new SqlParameter("@userID",SqlDbType.Int,4)};
            parameter[0].Value = userID;

            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameter);
            if( ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows[0]["UserID"] != null) { this.UserID = int.Parse(ds.Tables[0].Rows[0]["UserID"].ToString().Trim()); }
                if (ds.Tables[0].Rows[0]["UserName"] != null) { this.UserName = ds.Tables[0].Rows[0]["UserName"].ToString().Trim(); }
                if (ds.Tables[0].Rows[0]["UserGrade"] != null) { this.UserGrade = int.Parse(ds.Tables[0].Rows[0]["UserGrade"].ToString().Trim()); }
                if (ds.Tables[0].Rows[0]["UserPassword"] != null) { this.UserPassword = ds.Tables[0].Rows[0]["UserPassword"].ToString().Trim(); }
            }
        }

        //根据id得到名字
        public string getUserName(int userid)
        {
            string name = "";
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select UserName ");
            strSql.Append(" FROM [User] ");
            strSql.Append("where UserID=@userID");
            SqlParameter[] parameter = { 
                    new SqlParameter("@userID",SqlDbType.Int,4)};
            parameter[0].Value = userid;
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameter);

            if(ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows[0]["UserName"] != null) { name = ds.Tables[0].Rows[0]["UserName"].ToString().Trim(); }
            }
            return name;
        }

        //根据名字得到级别
        public int getUserGrade(string username)
        {
            int grade = 1;
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select UserGrade ");
            strSql.Append(" FROM [User] ");
            strSql.Append(" where UserName=@userName");
            SqlParameter[] parameter = { 
                    new SqlParameter("@userName", SqlDbType.VarChar,50)};
            parameter[0].Value = username;
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameter);

            if(ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows[0]["UserGrade"] != null) { grade = int.Parse(ds.Tables[0].Rows[0]["UserGrade"].ToString().Trim()); }
            }
            return grade;
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        /// 
        public int Add(string username)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into [User] (");
            strSql.Append("UserName)");
            strSql.Append(" values(");
            strSql.Append("@userName)");
            SqlParameter[] parameter = { 
                    new SqlParameter("@userName",SqlDbType.VarChar,50)};
            parameter[0].Value = username;

            object obj = DbHelperSQL.Query(strSql.ToString(), parameter);
            if (obj == null)
            {
                return 0;
            }
            else 
            {
                return Convert.ToInt32(obj);
            }
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int userid)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from [User] ");
            strSql.Append(" where UserID=" + UserID.ToString());

            int rows = DbHelperSQL.ExecuteSql(strSql.ToString());
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 获得数据列表
        /// </summary>
        /// 
        public DataSet GetList()
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * ");
            strSql.Append("FROM [User]");
            return DbHelperSQL.Query(strSql.ToString());
        }

        #endregion
    }
}
View Code
复制代码

 

对应数据库:

 

然后在xaml中设置下拉框:

 

复制代码
<UserControl x:Class="User.uc_login"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             Loaded="UserControl_Loaded"
             d:DesignHeight="1080" d:DesignWidth="1920">
    <Canvas x:Name="c_login" Width="1920" Height="1080" Background="Azure">
        <Canvas x:Name="c_log" Width="600" Height="600" Canvas.Left="680" Canvas.Top="100" Background="AntiqueWhite">
            <Label Content="用户:" Width="122" Height="80" FontSize="35" Canvas.Left="100" Canvas.Top="105" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
            <ComboBox x:Name="cb_uploader" Width="200" Height="80" Canvas.Left="268" Canvas.Top="105" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="35"/>
            <Label Content="密码:" Width="122" Height="80" FontSize="35" Canvas.Left="100" Canvas.Top="230" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
            <TextBox x:Name="tb_password" Width="200" Height="80" Canvas.Left="268" Canvas.Top="230" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="35"/>
            <Button Content="登录" Width="120" Height="60" FontSize="32" Canvas.Left="100" Canvas.Top="360" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Click="btn_login_Click"/>
            <!--<Button Content="修改密码" Width="165" Height="60" FontSize="32" Canvas.Left="305" Canvas.Top="460" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" />-->
        </Canvas>
    </Canvas>
</UserControl>
复制代码

注:上面代码xaml是用户控件代码。

 

 

 

最后,在后台代码设置:

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using User.sqlHelper;
using System.Data;

namespace User
{
    /// <summary>
    /// uc_login.xaml 的交互逻辑
    /// </summary>
    public partial class uc_login : UserControl
    {
        public uc_login()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            //获取下拉框用户名字
            User_test _u = new User_test();
            DataSet _ds = _u.GetList();
            if(_ds != null)
            {
                DataTable _dt = _ds.Tables[0];
                for (int i = 0; i < _dt.Rows.Count; i++)
                {
                    string UserName = _dt.Rows[i]["UserName"].ToString().Trim();
                    ComboBoxItem cbitem = new ComboBoxItem();
                    cb_uploader.Items.Add(cbitem);
                    cbitem.Content = UserName;
                }
            }
        }

        //登录按钮
        private void btn_login_Click(object sender, RoutedEventArgs e)
        {
            //判断下拉框不为空
            if (this.cb_uploader != null)
            {
                //判断密码不为空
                if (this.tb_password != null)
                {
                    string uploader = cb_uploader.Items.
                }
                //密码为空
                else
                { 
                    
                }
            }
            //下拉框为空
            else
            { 
                
            }
        }
    }
}
复制代码

结果:

 

posted @   Owen_ET  阅读(1307)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
  1. 1 イエスタデイ(翻自 Official髭男dism) 茶泡饭,春茶,kobasolo
  2. 2 模様 (TV size ver.) Ivy to Fraudulent Game
  3. 3 河口恭吾
  4. 4 愛してる 高鈴
  5. 5 一生所爱 卢冠廷,莫文蔚
  6. 6 世间美好与你环环相扣 柏松
  7. 7 理想三旬 陈鸿宇
  8. 8 不浪漫罪名 王杰
  9. 9 樱花树下 张敬轩
  10. 10 因为你在 达闻西乐队,福禄寿FloruitShow
  11. 11 悬溺 葛东琪
樱花树下 - 张敬轩
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

作词 : 林若宁

作曲 : 伍卓贤

树荫有一只蝉 跌落你身边

惊慌到失足向前

然后扑入我一双肩

令你腼腆一脸 像樱花万千

怀念美好高中两年

期望你的青春不变

去到今天

还记得樱花正开

还未懂跟你示爱

初春来时彼此约定过 继续期待

人置身这大时代

投入几番竞技赛

曾分开曾相爱

等待花蕊又跌下来

才洞悉这是恋爱

未有过的爱情 但有种温馨

未有过的爱情 但有种温馨

归家那单车小径

沿路细听你的歌声

没法再三倾听 你的感动昵称

维系错的一番友情

无奈已经不可纠正

太过坚贞

还记得樱花正开

还未懂跟你示爱

初春来时彼此闭着眼 渴望未来

人置身这大时代

投入几番竞技赛

曾分开曾相爱

等待跟你未爱的爱

你说悲不悲哀

秒速之间变改 小小世界

眷恋也许走不过 拆卸的街

少女亦随年渐长 走得多么快

如有天樱花再开

如有天樱花再开

期望可跟你示爱

当天园林 今天已换上满地青苔

如有天置地门外

乘电车跨过大海

匆匆跟你相望一眼 没理睬

明日花 昨日已开

点击右上角即可分享
微信分享提示