C#餐厅计费系统:ComboBox无法加载LocalDB数据求助
问题排查请求
本人熟悉C语言,接手C#餐厅计费记账软件项目,目前开发登录系统,使用MSSQLLocalDB。登录页用ComboBox展示UserID,但点击后为空,已尝试修改连接字符串无效。现附上相关代码,请求排查问题:
连接代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Adisyon01 { internal class cGenel { //public string conString = ("Server=(localdb)\\MSSQLLocalDB;Database=Restaurant2;Trusted_Connection=true"); public string conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Kerem Serinkan\\Restaurant2.mdf;Integrated Security=True;Connect Timeout=30"; public int _personelId; } }
登录验证代码
public bool personelEntryControl(string password,int UserId) { bool result = false; SqlConnection con = new SqlConnection(gnl.conString); SqlCommand cmd = new SqlCommand("SELECT * FROM employee WHERE id=@Id AND PASSWORD=@password0", con); cmd.Parameters.Add("@Id",SqlDbType.VarChar).Value = UserId; cmd.Parameters.Add("@password", SqlDbType.VarChar).Value = password; try { if(con.State==ConnectionState.Closed) { con.Open(); } result = Convert.ToBoolean(cmd.ExecuteScalar()); } catch (SqlException ex) { string hata = ex.Message; throw; } return result; }
数据读取代码
public void personelGetbyInformation(ComboBox cb) { cb.Items.Clear(); SqlConnection con = new SqlConnection(gnl.conString); SqlCommand cmd = new SqlCommand("SELECT * FROM employee", con); if (con.State == ConnectionState.Closed) { con.Open(); } SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { cPersoneller p = new cPersoneller(); p._personelId = Convert.ToInt32(dr["id"]); p._personelGorevId = Convert.ToInt32(dr["TASKID"]); p._personelAd = Convert.ToString(dr["NAME"]); p._personelSoyad= Convert.ToString(dr["SURNAME"]); p._personelParola= Convert.ToString(dr["PASSWORD"]); p._personelKullaniciAdi = Convert.ToString(dr["NICKNAME"]); p._personelDurum = Convert.ToBoolean(dr["STATUS"]); cb.Items.Add(p); } dr.Close(); con.Close(); }
排查关键点
ComboBox显示逻辑问题:直接将
cPersoneller对象添加到ComboBox时,默认调用ToString()方法。如果cPersoneller类未重写该方法,ComboBox会显示类的全名而非UserID。解决方法二选一:- 在
cPersoneller类中重写ToString(),返回_personelId(或你想展示的字段):public override string ToString() { return _personelId.ToString(); } - 设置ComboBox的
DisplayMember属性,指定要显示的对象属性名:cb.DisplayMember = "_personelId";
- 在
数据库连接有效性验证:
- 确认
Restaurant2.mdf文件路径C:\\Users\\Kerem Serinkan\\Restaurant2.mdf是否存在,当前程序是否有读取权限。 - 在
personelGetbyInformation方法中添加异常捕获,输出具体错误信息,排查是否是连接失败导致无数据加载:try { // 现有代码... } catch (Exception ex) { MessageBox.Show("数据加载失败:" + ex.Message); }
- 确认
数据读取正确性检查:
- 确认
employee表中存在有效数据。 - 检查
dr["id"]、dr["TASKID"]等字段名是否与数据库表中字段完全匹配(注意拼写和大小写,SQL Server默认不区分大小写,但需避免拼写错误)。
- 确认
登录代码的参数错误(附带修复):SQL语句中使用的参数是
@password0,但代码中添加的参数是@password,参数名不匹配会导致登录验证失败,建议修改为:cmd.Parameters.Add("@password0", SqlDbType.VarChar).Value = password;
内容的提问来源于stack exchange,提问作者Fakeboss20
相关产品推荐
相关产品推荐

