标签:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace _15._2DataGridView绑定数据源 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { dgvBindMode.DataSource = BindModeSource().Tables[0];//数据集可以包含多张表格,调用时候需要指定 dgvNonBindMode.DataSource = nonBindSource(); } private DataSet BindModeSource() { string constr = "Server=.;uid=sa;pwd=zqyo850619;database=csharpzxw"; SqlConnection mycon = new SqlConnection(constr); DataSet myds = new DataSet();//申明一个数据集 try { mycon.Open(); string sql = "select name,gender from mytable001"; SqlDataAdapter myda = new SqlDataAdapter(sql, mycon);//申明一个数据适配器,包括数据库查询语言 和连接的数据源信息 myda.Fill(myds,"mytable001");//适配器将数据源种的表装载到数据集中
} catch(Exception ex) { MessageBox.Show(ex.Message); } finally { mycon.Close(); } return myds; } private DataTable nonBindSource() { DataTable mydt = new DataTable(); mydt.Columns.Add("name", Type.GetType("System.String")); mydt.Columns.Add("gender", Type.GetType("System.String")); string[,] mystr = { { "张三", "女" }, { "李四", "男" }, { "王五", "男" }, { "赵六", "女" }, { "何七", "男" } }; for(int i = 0; i < mystr.Length / 2; i++) { DataRow mydr = mydt.NewRow(); mydr[0] = mystr[i, 0]; mydr[1] = mystr[i, 1]; mydt.Rows.Add(mydr); } return mydt; } } }
标签:
原文地址:http://www.cnblogs.com/zqyo2000z/p/5361278.html