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

绑定数据:
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.         }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值