C#编程-70:dataGridView绑定数据源_彭世瑜_新浪博客

263 阅读1分钟

绑定数据:

1、绑定模式

2、代码模式

举例如下:

  1. private void Form1_Load(object sender, EventArgs e)

  2.         {

  3.             // TODO:  这行代码将数据加载到表“companyDataSet.clerk”中。您可以根据需要移动或删除它。

  4.             //this.clerkTableAdapter.Fill(this.companyDataSet.clerk);

  5.             dataGridView1.DataSource=BindModeSource().Tables[0];

  6.             dataGridView2.DataSource = NonBindSource();

  7.         }

  8.         private DataSet BindModeSource()

  9.         {

  10.             string constr = @"server=(localdb)\Projects;integrated security=sspi;database=company";

  11.             SqlConnection sqlcon = new SqlConnection(constr);

  12.             DataSet dataSet = new DataSet();

  13.             try

  14.             {

  15.                 sqlcon.Open();

  16.                 string sql = "select name,gender from clerk";

  17.                 SqlDataAdapter sqladp = new SqlDataAdapter(sql,sqlcon);               

  18.                 sqladp.Fill(dataSet,"clerk");

  19.             }

  20.             catch(Exception ex)

  21.             {

  22.                 MessageBox.Show(ex.Message);

  23.             }

  24.             finally

  25.             {

  26.                 sqlcon.Close();

  27.             }

  28.             return dataSet;

  29.         }

  30.         private DataTable NonBindSource()

  31.         {

  32.             DataTable table = new DataTable();

  33.             //添加表头

  34.             table.Columns.Add("name", Type.GetType("System.String"));

  35.             table.Columns.Add("gender", Type.GetType("System.String"));

  36.             string[,] strs = { {

    "张三","男"},{

    "李四","男"},{

    "王五","男"},{

    "张三","男"},{

    "张三","男"}};

  37.             //添加行记录

  38.             for (int i = 0; i < strs.Length / 2; i++)

  39.             {

  40.                 DataRow row = table.NewRow();

  41.                 row[0] = strs[i, 0];

  42.                 row[1] = strs[i, 1];

  43.                 table.Rows.Add(row);

  44.  

  45.             }

  46.                 return table;

  47.         }