天天看点

C#编程-70:dataGridView绑定数据源

绑定数据:

1、绑定模式

2、代码模式

举例如下:

private void Form1_Load(object sender, EventArgs e)
        {
            // TODO:  这行代码将数据加载到表“companyDataSet.clerk”中。您可以根据需要移动或删除它。
            //this.clerkTableAdapter.Fill(this.companyDataSet.clerk);
            dataGridView1.DataSource=BindModeSource().Tables[0];
            dataGridView2.DataSource = NonBindSource();
        }
        private DataSet BindModeSource()
        {
            string constr = @"server=(localdb)\Projects;integrated security=sspi;database=company";
            SqlConnection sqlcon = new SqlConnection(constr);
            DataSet dataSet = new DataSet();
            try
            {
                sqlcon.Open();
                string sql = "select name,gender from clerk";
                SqlDataAdapter sqladp = new SqlDataAdapter(sql,sqlcon);               
                sqladp.Fill(dataSet,"clerk");
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                sqlcon.Close();
            }
            return dataSet;
        }
        private DataTable NonBindSource()
        {
            DataTable table = new DataTable();
            //添加表头
            table.Columns.Add("name", Type.GetType("System.String"));
            table.Columns.Add("gender", Type.GetType("System.String"));
            string[,] strs = { {"张三","男"},{"李四","男"},{"王五","男"},{"张三","男"},{"张三","男"}};
            //添加行记录
            for (int i = 0; i < strs.Length / 2; i++)
            {
                DataRow row = table.NewRow();
                row[0] = strs[i, 0];
                row[1] = strs[i, 1];
                table.Rows.Add(row);
 
            }
                return table;
        }