Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to populate datagridview combobox with data from database. I added this combobox programatically.

What I have tried:

This is my code for adding column to the datagridview. i have added combobox also
C#
public void bind_grid()
        {
            table.Columns.Add("SalesSno", typeof(int));
            table.Columns.Add("Item_Description", typeof(string));
            table.Columns.Add("Quantity", typeof(int));
            table.Columns.Add("Converstion_Type", typeof(int));
            table.Columns.Add("Rate", typeof(double));
            table.Columns.Add("amount", typeof(double));
            table.Columns.Add("invoiceNo", typeof(string));

            table.Rows.Add();

            grdsearch.DataSource = table;

            grdsearch.GridColor = Color.FromArgb(211, 225, 229);
            grdsearch.BackgroundColor = Color.Wheat;

            grdsearch.RowsDefaultCellStyle.BackColor = Color.AliceBlue;
            grdsearch.RowsDefaultCellStyle.SelectionBackColor = Color.CornflowerBlue;
            grdsearch.RowsDefaultCellStyle.SelectionForeColor = Color.White;

            grdsearch.Columns.Add(HSN_Code);
            
            Units.HeaderText = "Units";
            Units.Name = "Units";
            grdsearch.Columns.Add(Units);
        }

        private void HSN_CodePopulate()
        {
            connection();
            SqlCommand cmd;
            cmd = new SqlCommand("", con);
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            
            cmd.CommandText = "select * from HSNTable";
            cmd.ExecuteNonQuery();
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adp.Fill(dt);

            DataRow row = dt.NewRow();
            row[0] = 0;
            row[1] = "Please select";
            dt.Rows.InsertAt(row, 0);

            try
            {
                HSN_Code.DataSource = dt;
                HSN_Code.HeaderText = "HSN_Code";
                HSN_Code.Name = "HSN_Code";
            }
            catch(Exception exc)
            {
                MessageBox.Show(exc.Message);
            }

        }

can you please help me how should i proceed as this code is showing something like System.Data.DataRowView in combobox.
Posted
Updated 5-Jun-19 7:08am
v2

Here is an example: https://www.encodedna.com/2013/02/show-combobox-datagridview.htm[^]
Note that the ComboBox will have the same values for every row.

This might be more to your liking: c# - datagridview with datasource and combobox - Stack Overflow[^]
 
Share this answer
 
v2
Comments
MukulMohal 5-Jun-19 5:57am    
i did had a look to this solution but this is not working as in this solution columns are added from property window not programatically. and there is no code to populate datagridviewcombobox with data from data base.
RickZeeland 5-Jun-19 7:21am    
Yes, the first example is not that fantastic I'm afraid. I must have some code somewhere doing a similar thing, but I can not access it as I'm at work at the moment, promise to look for it this evening !
MukulMohal 5-Jun-19 8:29am    
i was able to populate the combobox1. but when i added combobox2 in the same grid it over written the combobox1. i dont know how should i go for it.

AND IN THE ABOVE CODE I JUST REPLACED

try
{
HSN_Code.DataSource = dt;
HSN_Code.HeaderText = "HSN_Code";
HSN_Code.Name = "HSN_Code";
}

with

try
{
HSN_Code.DataSource = dt1;
HSN_Code.HeaderText = "HSN Code";
HSN_Code.Name = "HSN_Code";
HSN_Code.DisplayMember = "HSN_Code";
HSN_Code.ValueMember = "Id";
}
RickZeeland 5-Jun-19 8:49am    
You can only have one type of ComboBox with the same values for all grid rows, or you would have to resort to some "on the fly trickery" :)
MukulMohal 5-Jun-19 8:50am    
is there any way to add multiple datagridviewcombobox in same datagridview?
Here is an example with a ComboBox and a DateTimePicker:
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Forms;

namespace TestForm1
{
    /// <summary>
    /// Test data grid with BindingList.
    /// Replace column with ComboBox.
    /// Replace date column with class CalendarColumn.
    /// </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();
            this.AddCalendarColumn();

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

        /// <summary>
        /// http://www.codeproject.com/Articles/38972/Nullable-datetime-column-in-NET-DataGrid-with-Date
        /// </summary>
        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;
            }
        }

        /// <summary>
        /// Uses class CalendarColumn.
        /// https://msdn.microsoft.com/en-us/library/7tas5c80(v=vs.100).aspx
        /// </summary>
        private void AddCalendarColumn()
        {
            CalendarColumn col = new CalendarColumn();
            col.Name = "Datum";
            col.Width = 100;
            this.dataGridView1.Columns.Add(col);
            ////this.dataGridView1.Columns["Datum"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm";   // "dd/MM/yyyy";

            foreach (DataGridViewRow row in this.dataGridView1.Rows)
            {
                row.Cells["Datum"].Value = bindingList[row.Index].date;
            }
        }

        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);
            }
            else if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Datum")
            {
                ////DateTime oldDate = this.bindingList[e.RowIndex].date;
                DateTime newDate;
                DateTime.TryParse(this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(), out newDate);
                this.bindingList[e.RowIndex].date = newDate;
            }
        }

        /// <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"
            this.dataGridView1.Rows[this.bindingList.Count - 1].Cells["Datum"].Value = item.date; 
        }
    }
}

dgvClass1.cs
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();
    }
}

CalendarColumn.cs
namespace TestForm1
{
    using System;
    using System.Windows.Forms;

    /// <summary>
    /// How to: Host Controls in Windows Forms DataGridView Cells
    /// https://msdn.microsoft.com/en-us/library/7tas5c80(v=vs.100).aspx
    /// </summary>
    public class CalendarColumn : DataGridViewColumn
    {
        public CalendarColumn()
            : base(new CalendarCell())
        {
        }

        public override DataGridViewCell CellTemplate
        {
            get
            {
                return base.CellTemplate;
            }
            set
            {
                // Ensure that the cell used for the template is a CalendarCell.
                if (value != null &&
                    !value.GetType().IsAssignableFrom(typeof(CalendarCell)))
                {
                    throw new InvalidCastException("Must be a CalendarCell");
                }
                base.CellTemplate = value;
            }
        }
    }

    public class CalendarCell : DataGridViewTextBoxCell
    {

        public CalendarCell()
            : base()
        {
            // Use the short date format.
            this.Style.Format = "d";
        }

        public override void InitializeEditingControl(int rowIndex, object
            initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
        {
            // Set the value of the editing control to the current cell value.
            base.InitializeEditingControl(rowIndex, initialFormattedValue,
                dataGridViewCellStyle);
            CalendarEditingControl ctl =
                DataGridView.EditingControl as CalendarEditingControl;
            // Use the default row value when Value property is null.
            if (this.Value == null)
            {
                ctl.Value = (DateTime)this.DefaultNewRowValue;
            }
            else
            {
                ctl.Value = (DateTime)this.Value;
            }
        }

        public override Type EditType
        {
            get
            {
                // Return the type of the editing control that CalendarCell uses.
                return typeof(CalendarEditingControl);
            }
        }

        public override Type ValueType
        {
            get
            {
                // Return the type of the value that CalendarCell contains.

                return typeof(DateTime);
            }
        }

        public override object DefaultNewRowValue
        {
            get
            {
                // Use the current date and time as the default value.
                return DateTime.Now;
            }
        }
    }

    class CalendarEditingControl : DateTimePicker, IDataGridViewEditingControl
    {
        DataGridView dataGridView;
        private bool valueChanged = false;
        int rowIndex;

        public CalendarEditingControl()
        {
            this.Format = DateTimePickerFormat.Short;
            //this.Format = DateTimePickerFormat.Custom;
            //this.CustomFormat = "yyyy-MM-dd HH:mm";
        }

        // Implements the IDataGridViewEditingControl.EditingControlFormattedValue 
        // property.
        public object EditingControlFormattedValue
        {
            get
            {
                return this.Value.ToShortDateString();
            }
            set
            {
                if (value is String)
                {
                    try
                    {
                        // This will throw an exception of the string is 
                        // null, empty, or not in the format of a date.
                        this.Value = DateTime.Parse((String)value);
                    }
                    catch
                    {
                        // In the case of an exception, just use the 
                        // default value so we're not left with a null
                        // value.
                        this.Value = DateTime.Now;
                    }
                }
            }
        }

        // Implements the 
        // IDataGridViewEditingControl.GetEditingControlFormattedValue method.
        public object GetEditingControlFormattedValue(
            DataGridViewDataErrorContexts context)
        {
            return EditingControlFormattedValue;
        }

        // Implements the 
        // IDataGridViewEditingControl.ApplyCellStyleToEditingControl method.
        public void ApplyCellStyleToEditingControl(
            DataGridViewCellStyle dataGridViewCellStyle)
        {
            this.Font = dataGridViewCellStyle.Font;
            this.CalendarForeColor = dataGridViewCellStyle.ForeColor;
            this.CalendarMonthBackground = dataGridViewCellStyle.BackColor;
        }

        // Implements the IDataGridViewEditingControl.EditingControlRowIndex 
        // property.
        public int EditingControlRowIndex
        {
            get
            {
                return rowIndex;
            }
            set
            {
                rowIndex = value;
            }
        }

        // Implements the IDataGridViewEditingControl.EditingControlWantsInputKey 
        // method.
        public bool EditingControlWantsInputKey(
            Keys key, bool dataGridViewWantsInputKey)
        {
            // Let the DateTimePicker handle the keys listed.
            switch (key & Keys.KeyCode)
            {
                case Keys.Left:
                case Keys.Up:
                case Keys.Down:
                case Keys.Right:
                case Keys.Home:
                case Keys.End:
                case Keys.PageDown:
                case Keys.PageUp:
                    return true;
                default:
                    return !dataGridViewWantsInputKey;
            }
        }

        // Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit 
        // method.
        public void PrepareEditingControlForEdit(bool selectAll)
        {
            // No preparation needs to be done.
        }

        // Implements the IDataGridViewEditingControl
        // .RepositionEditingControlOnValueChange property.
        public bool RepositionEditingControlOnValueChange
        {
            get
            {
                return false;
            }
        }

        // Implements the IDataGridViewEditingControl
        // .EditingControlDataGridView property.
        public DataGridView EditingControlDataGridView
        {
            get
            {
                return dataGridView;
            }
            set
            {
                dataGridView = value;
            }
        }

        // Implements the IDataGridViewEditingControl
        // .EditingControlValueChanged property.
        public bool EditingControlValueChanged
        {
            get
            {
                return valueChanged;
            }
            set
            {
                valueChanged = value;
            }
        }

        // Implements the IDataGridViewEditingControl
        // .EditingPanelCursor property.
        public Cursor EditingPanelCursor
        {
            get
            {
                return base.Cursor;
            }
        }

        protected override void OnValueChanged(EventArgs eventargs)
        {
            // Notify the DataGridView that the contents of the cell
            // have changed.
            valueChanged = true;
            this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
            base.OnValueChanged(eventargs);
        }
    }
}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900