using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;
namespace dataviewcombox
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//通过应用程序配置文件创建数据库链接
string constr = ConfigurationManager.ConnectionStrings["strcon"].ConnectionString;
private void Form1_Load(object sender, EventArgs e)
{
#region//把数据库显示出来
dataGridView1.AllowUserToAddRows = false;//是否允许添加行
dataGridView1.AutoGenerateColumns = false;//是否允许自动添加列
using (SqlConnection sqlcon = new SqlConnection(constr))
{
sqlcon.Open();//打开数据库
string sql1 = "select * from [ClassTable]";//查出所有字段
string sql2 = "select Adept from [ClassTable]";//查出系别字段
DataGridViewComboBoxColumn dgvComboBoxColumn = dataGridView1.Columns["Adept"] as DataGridViewComboBoxColumn;
dgvComboBoxColumn.DataPropertyName = "Adept";//把显示的字段名和数据库的字段名绑定
dgvComboBoxColumn.DataSource = ShowData(sql2).DefaultView;//必须在设置dataGridView1的DataSource的属性前设置
dgvComboBoxColumn.DisplayMember = "Adept";//组合框要显示字符串的列
dgvComboBoxColumn.ValueMember = "Adept"; //下拉列表选项的值
dataGridView1.DataSource = ShowData(sql1).DefaultView;//绑定数据库
}
#endregion
}
public DataTable ShowData(string sql)
{
#region//自定义数据库显示函数
using (SqlConnection con=new SqlConnection(constr))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(sql, con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
#endregion
}
}
}
//注释:注意事项截图如下:
//配置程序截图
//功能界面测试截图