发布网友 发布时间:2022-04-26 19:57
共2个回答
懂视网 时间:2022-05-02 15:15
public static SqlDataReader GetReader(string sql) 2 { 3 SqlConnection conn = new SqlConnection(connString); 4 SqlCommand cmd = new SqlCommand(sql, conn); 5 try 6 { 7 conn.Open(); 8 return cmd.ExecuteReader(CommandBehavior.CloseConnection); 9 } 10 catch (Exception ex) 11 { 12 conn.Close(); 13 //将错误信息写入日志... 14 15 throw ex; 16 } 17 }
封装到集合中:
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
热心网友 时间:2022-05-02 12:23
combobox.DataBindings.Add("要绑定控件的属性如下拉框的SelectedValue\Text", 数据源如dataset1, "导航路径如Table1.ListID");