combobox绑定数据库与datagridview绑定数据库

1.combobox绑定数据库
   在面页加载事件中绑定:
  SqlConnection connection = new SqlConnection(connectionString)
  DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
  this.combobox1.DataSource = ds.Tables[0];
      this.combobox1.ValueMember = "字段名";//下拉框绑定的值,一般与displaymember一一对应;
      this.combobox1.DisplayMember = "字段名"; //下拉框中显示的值。 
  
  this.combobox1.SelectedValue.ToString();//这是下拉框中的值被选定后,获得的被选项。

combobox1.DropDownStyle = ComboBoxStyle.DropDownList;//限制combobox的内容不能被用户编辑,只能从下拉表中选

2.datagridview绑定数据库

  SqlConnection connection = new SqlConnection(connectionString)
  DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }

  this.dataGridView1.DataSource = ds;
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataMember = ds.Tables[0].TableName;
            dataGridView1.ReadOnly = true;
然后在datagridview的编辑中添加显示的列名,并将每列的datapropertyname属性与数据库中的字段一一对应(绑定)。

3.当下拉框中的内容发生改变时引的的事件一般是selectionchangecommitted事件。

posted on 2012-04-17 09:54 SkyDream 阅读(1240) 评论(0)  编辑  收藏 所属分类: C# WinForm

<2012年4月>
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

导航

统计

常用链接

留言簿(3)

随笔分类

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜