时间:2021-07-01 10:21:17 帮助过:11人阅读
封装到集合中:
1 public List<StudentClass> GetAllClasses() 2 { 3 string sql = "select ClassName,ClassId from StudentClass"; 4 SqlDataReader objReader = SQLHelper.GetReader(sql); 5 List<StudentClass> list = new List<StudentClass>(); 6 while (objReader.Read()) 7 { 8 list.Add(new StudentClass() 9 { 10 ClassId = Convert.ToInt32(objReader["ClassId"]), 11 ClassName = objReader["ClassName"].ToString() 12 }); 13 } 14 objReader.Close(); 15 return list; 16 }
然后在窗体初始化方法里面调用并绑定数据:
1 private StudentClassService objClassService = new StudentClassService(); 2 3 public FrmAddStudent() 4 { 5 InitializeComponent(); 6 //初始化班级下拉框 7 this.cboClassName.DataSource = objClassService.GetAllClasses(); 8 this.cboClassName.DisplayMember = "ClassName"; 9 this.cboClassName.ValueMember = "ClassId"; 10 11 }
第二种情况:
SQLHelper类中的代码:
1 public static DataSet GetDataSet(string sql) 2 { 3 SqlConnection conn = new SqlConnection(connString); 4 //SqlCommand cmd = new SqlCommand(sql, conn); 5 SqlDataAdapter da = new SqlDataAdapter(sql, conn); 6 DataSet ds = new DataSet(); 7 da.Fill(ds); 8 return ds; 9 }
然后在窗体初始化方法里面调用并绑定数据:
1 public partial class FrmVoucherQuery : Form 2 { 3 public FrmVoucherQuery() 4 { 5 InitializeComponent(); 6 string sql = string.Format("Select FName From t_VoucherGroup Order by FGroupID"); 7 //控件名.DataSource=数据集.数据表 8 cbVoucherName.DataSource = SQLHelper.GetDataSet(sql).Tables[0]; 9 cbVoucherName.DisplayMember = "FName"; 10 cbVoucherName.ValueMember = "FName"; 11 } 12 }
Winform开发中如何将数据库字段绑定到ComboBox控件
标签:对象 cep ... stat inf form 方法 splay rom