我如何将mdf文件加载到datagridview combobo [英] How I load mdf file to datagridview combobo

查看:52
本文介绍了我如何将mdf文件加载到datagridview combobo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建包含组合的动态datagridview。我刚刚创建了arraylist,它包含了用于组合数据源的数据表。但是我还是无法解决这个问题。



我尝试了什么:



i want to create dynamic datagridview which contain combo in it. i just created arraylist which holds a datatable for datasource for combo. but i cant solve this problem yet.

What I have tried:

private void PaymentVoucher_Load(object sender, EventArgs e)
       {

           if (con.State == ConnectionState.Closed)
           {
               con.Open();
           }
           DataTable dt = new DataTable();
           SqlDataAdapter da = new SqlDataAdapter("selectCustomer", con);
           da.SelectCommand.CommandType = CommandType.StoredProcedure;
           da.Fill(dt);
           ArrayList arr = new ArrayList();
           foreach(DataRow dr in dt.Rows)
           {
               arr.Add(dr);
           }
           var cmbcell = new DataGridViewComboBoxCell();
           foreach (DataRow dr in dt.Rows)
           {
               int n = dgv_Payment.Rows.Add();
               cmbcell.DataSource = arr;
               dgv_Payment.Rows[n].Cells["cNameCombo"] = cmbcell;
               cmbcell.ValueMember = "cust_id";
               cmbcell.DisplayMember = "custName";

           }

           con.Close();
       }

推荐答案

这是一个(粗略)示例:C# - 使用SQL Source - Stack Overflow在数据网格视图中填充组合框 [ ^ ]



此处使用SQL Server的示例: C#tutorial- DataGridView显示来自SQL Server数据库的表 [ ^ ]



另一个ComboBox示例:将ComboBox添加到C#DataGridView [ ^ ]





我还在我的项目中找到了一些代码:

Here is a (crude) example: C# - Fill a combobox in a datagridview using SQL Source - Stack Overflow[^]

Example on using SQL Server here: C# tutorial- DataGridView to display table from SQL Server database[^]

And another ComboBox example: Add ComboBox to C# DataGridView[^]


I also found some code in my projects:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

namespace TestForm1
{
    /// <summary>
    /// Test data grid with BindingList.
    /// Replace column with ComboBox.
    /// </summary>
    public partial class Form5 : Form
    {
        public BindingList<dgvClass1> bindingList;

        public Form5()
        {
            InitializeComponent();

            // Allow user to resize column widths.
            this.dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
            this.dataGridView1.AllowUserToAddRows = false;

            this.dataGridView1.DataBindingComplete += (s, ev) => Debug.WriteLine("BindingComplete");
            //this.dataGridView1.CurrentCellDirtyStateChanged += new DataGridViewRowEventHandler(this.DataGridChanged);
            this.dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged);
            this.dataGridView1.RowValidated += new DataGridViewCellEventHandler(this.RowValidatedEvent);
        }

        /// <summary>
        /// Fill the BindingList and set the dataGridView1.DataSource.
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            bindingList = new BindingList<dgvClass1>();
            bindingList.AllowNew = true;
            bindingList.AllowRemove = true;

            if (this.dataGridView1.DataSource != null)
            {
                this.dataGridView1.DataSource = null;
                this.dataGridView1.Columns.Remove("Priority");
            }

            this.AddTestData();
            this.AddComboBox();

            bindingList.AddingNew += (s, ev) => Debug.WriteLine("AddingNew");
            bindingList.ListChanged += (s, ev) => Debug.WriteLine("ListChanged");
        }

        private void AddTestData()
        {
            // Add row with test data.
            var item = new dgvClass1();
            item.Number = 1;
            item.Name = "Test data1";
            item.priority = "Low";          // Not visible field will be used in ComboBox later.
            bindingList.Add(item);

            // Add row with test data.
            item = new dgvClass1();
            item.Number = 2;
            item.Name = "Test data2";
            item.date = item.date.AddMonths(1);
            bindingList.Add(item);

            // Add row with test data.
            item = new dgvClass1();
            item.Number = 3;
            item.Name = "Test data3";
            item.date = item.date.AddMonths(2);
            bindingList.Add(item);

            var clone = (dgvClass1)item.Clone();
            clone.Number++;
            bindingList.Add(clone);

            clone = (dgvClass1)clone.Clone();
            clone.Number++;
            bindingList.Add(clone);

            this.dataGridView1.DataSource = bindingList;
            this.dataGridView1.Columns[0].Frozen = true;

            //this.dataGridView1.Columns[1].ValueType = typeof(int); 
        }

        /// <summary>
        /// Add ComboBox column at position 2.
        /// </summary>
        private void AddComboBox()
        {
            DataGridViewComboBoxColumn dgvCombo = new DataGridViewComboBoxColumn();
            dgvCombo.Name = "Priority";
            dgvCombo.Width = 100;
            dgvCombo.DataSource = new string[] { "Low", "Medium", "High" };
            dgvCombo.DisplayIndex = 2;
            this.dataGridView1.Columns.Add(dgvCombo);

            for (int rowNr = 0; rowNr < bindingList.Count; rowNr++)
            {
                var row = this.dataGridView1.Rows[rowNr];
                DataGridViewComboBoxCell dgvComboCell = (DataGridViewComboBoxCell)row.Cells["Priority"];
                dgvComboCell.Value = bindingList[row.Index].priority;
            }
        }

        public void DataGridChanged(object sender, DataGridViewRowEventArgs e)
        {
            Debug.Print("CollectionChanged");
        }

        private void RowValidatedEvent(object sender, DataGridViewCellEventArgs e)
        {
            Debug.Print("RowValidatedEvent");
        }

        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Priority")
            {
                string oldPriority = this.bindingList[e.RowIndex].priority;
                string newPriority = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                this.bindingList[e.RowIndex].priority = newPriority;
                //this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Yellow;
                Debug.Print("Priority changed from: " + oldPriority + " to: " + newPriority);
            }
        }

        /// <summary>
        /// Show changes in bindingList.
        /// </summary>
        private void button2_Click(object sender, EventArgs e)
        {
            string str = string.Empty;

            foreach (var item in this.bindingList)
            {
                str += item.Name + ", " + item.priority + ", " + item.date + "\n";
            }

            MessageBox.Show(str);
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.CurrentRow != null)
            {
                this.bindingList.RemoveAt(this.dataGridView1.CurrentRow.Index);
            }
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            var item = new dgvClass1();
            bindingList.Add(item);
            this.dataGridView1.Rows[this.bindingList.Count - 1].Cells["Priority"].Value = item.priority;    // "Medium"
        }
    }
}





并添加此辅助类:



And add this helper class:

using System;

namespace TestForm1
{
    public class dgvClass1 : ICloneable
    {
        /// <summary>
        /// priority is not a propery, so it is not visible in datagrid by default.
        /// </summary>
        public string priority;

        /// <summary>
        /// date is not a propery, so it is not visible in datagrid by default.
        /// </summary>
        public DateTime date;

        public int Number { get; set; }
        public string Name { get; set; }

        public dgvClass1()
        {
            this.date = DateTime.Now;
            this.priority = "Medium";
        }

        /// <summary>
        /// https://msdn.microsoft.com/en-us/library/system.object.memberwiseclone(v=vs.100).aspx
        /// </summary>
        public object Clone()
        {
            return (dgvClass1)this.MemberwiseClone();
        }
    }
}


这篇关于我如何将mdf文件加载到datagridview combobo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆