日期:2014-05-16 浏览次数:20439 次
DataSet ds = new DataSet("mydb"); DataTable table = new DataTable("mytable"); table.CaseSensitive = false; table.MinimumCapacity = 100; table.TableName = "emp"; DataColumn colEmpno = new DataColumn(); colEmpno.ColumnName = "empno"; colEmpno.DataType = typeof(int); colEmpno.AutoIncrement = true; //设置自增长 colEmpno.AutoIncrementSeed = 1000; colEmpno.AutoIncrementStep = 1; table.Columns.Add(colEmpno); table.Columns.Add(new DataColumn("empname", typeof(string))); table.Columns.Add(new DataColumn("hiredate", typeof(System.DateTime))); DataRow row1 = table.NewRow(); //增加数据 //row1["empno"] = 1000; row1["empname"] = "apq"; row1["hiredate"] = DateTime.Parse("2009-1-9"); table.Rows.Add(row1); DataRow row2 = table.NewRow(); //增加数据 //row2["empno"] = 1001; row2["empname"] = "bob"; row2["hiredate"] = DateTime.Parse("2008-5-1"); table.Rows.Add(row2); ds.Tables.Add(table); dataGridView1.DataSource = table;
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.Configuration; namespace SqlDataAdapterTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string connStr = ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString; SqlConnection conn = new SqlConnection(connStr); conn.Open(); string sql = "select * from emp"; SqlDataAdapter adapter = new SqlDataAdapter(sql, conn); DataSet ds = new DataSet(); //adapter.Fill(ds); //dataGridView1.DataSource = ds.Tables[0]; //显示数据 adapter.Fill(ds, "emp"); //给表起个名字 dataGridView1.DataSource = ds; dataGridView1.DataMember = "emp"; conn.Dispose(); conn.Close(); } private void button2_Click(object sender, EventArgs e) { string connStr = ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString; SqlConnection conn = new SqlConnection(connStr); conn.Open(); string sql = "select * from emp"; SqlDataAdapter adapter = new SqlDataAdapter(sql, conn); DataTable table = new DataTable("emp"); adapter.Fill(table); dataGridView1.DataSource = table.DefaultView; //和dataGridView控件绑定数据 conn.Dispose(); conn.Close(); } //用DataTable加载SqlDataReader指向的对象 private void button3_Click(object sender, EventArgs e) { string connStr = ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString; SqlConnection conn = new SqlConnection(connStr); conn.Open(); string sql = "select * from emp"; SqlCommand cmd = new SqlCommand(sql, conn); SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); DataTable table = new DataTable("emp"); table.Load(reader); dataGridView1.DataSource = table; reader.Close(); } } }