从访问数据库 - combobox构建的Datagridview

时间:2016-12-06 00:16:14

标签: c# asp.net datagridview combobox

我安装本教程以帮助我在来自数据库的datagridview中显示组合框。
我需要使用SQL DATA SOURCE我通常编写所有代码,所以我不习惯使用它。如果我要显示10个组合框,我是否需要为每个组合框创建一个数据源?

https://msdn.microsoft.com/en-us/library/ms178294.aspx

谢谢

2 个答案:

答案 0 :(得分:1)

我认为这会对你有帮助。

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            dataGridView1.ColumnCount = 3;
            dataGridView1.Columns[0].Name = "Product ID";
            dataGridView1.Columns[1].Name = "Product Name";
            dataGridView1.Columns[2].Name = "Product Price";

            string[] row = new string[] { "1", "Product 1", "1000" };
            dataGridView1.Rows.Add(row);
            row = new string[] { "2", "Product 2", "2000" };
            dataGridView1.Rows.Add(row);
            row = new string[] { "3", "Product 3", "3000" };
            dataGridView1.Rows.Add(row);
            row = new string[] { "4", "Product 4", "4000" };
            dataGridView1.Rows.Add(row);

            DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
            cmb.HeaderText = "Select Data";
            cmb.Name = "cmb";
            cmb.MaxDropDownItems = 4;
            cmb.Items.Add("True");
            cmb.Items.Add("False");
            dataGridView1.Columns.Add(cmb);

        }
    }
}

此外,这是从Access加载DataGridView的有效方法。

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=your .mdb file;";
            string sql = "SELECT * FROM Authors";
            OleDbConnection connection = new OleDbConnection(connetionString);
            OleDbDataAdapter dataadapter = new OleDbDataAdapter(sql, connection);
            DataSet ds = new DataSet();
            connection.Open();
            dataadapter.Fill(ds, "Authors_table");
            connection.Close();
            dataGridView1.DataSource = ds;
            dataGridView1.DataMember = "Authors_table";
        }
    }
}

答案 1 :(得分:0)

如果您为多个控件重复使用相同的数据源,那么您将获得所有组合框的相同数据集。您可以仅从单个select语句设置值成员并显示组合的成员。如果您的要求没问题,那么您可以重复使用相同的数据源。