语法:
public static DataTable ExecuteTable(string sql) { using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); SqlCommand cmd = new SqlCommand(sql, conn); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adapter.Fill(ds); return ds.Tables[0]; } }
使用: 在窗体加载的时候调用 ExecuteTable
private void FrmAddStudent_Load(object sender, EventArgs e) { string sql = "select * from StudentClass"; DataTable dataTable = SqlHelper.ExecuteTable(sql); //向集合第一个位置插入一条数据 DataRow dr = dataTable.NewRow(); dr["ClassId"] = 0; dr["ClassName"] = "请选择班级"; dataTable.Rows.InsertAt(dr, 0); this.comboBox1.DataSource = dataTable; this.comboBox1.DisplayMember = "ClassName"; this.comboBox1.ValueMember = "ClassId"; }
展示:
标签:数据,sql,DataSet,使用,new,dr,dataTable,conn From: https://www.cnblogs.com/tlfe/p/18247174