Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtime disable the datagridviewcombobox

Tags:

c#

winforms

How do I change the following things of a DataGridViewComboBoxColumn at runtime:

  1. How do I set the first value of the combo box as default?
  2. Disable combo box/make it read-only while showing the first value as default. Meaning to say, if I have 3 items in the combo-box it should show only the first item. (Either disable the combo box drop down, or change it to become a text box at runtime).

Reason:
The reason I do that is because for my Enum I have Status{New=1,Stop=2,Temp=3}. When i want to register a student, the status is always set to New. So when I save, it will auto save the Status = 1.

like image 366
VeecoTech Avatar asked Mar 21 '11 03:03

VeecoTech


1 Answers

Here is how to set the default value and disable the cell:

using System;
using System.Windows.Forms;

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

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            Column1.DataSource = new int[] { 1, 2, 3 };
            Column1.DataPropertyName = "Number";
            dataGridView1.DataSource = new[] 
            { 
                new { Number=1 },
                new { Number=2 },
                new { Number=3 },
                new { Number=1 }
            };
        }

        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == Column1.Index && e.RowIndex == (dataGridView1.Rows.Count - 1))
            {
                DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)dataGridView1[e.ColumnIndex, e.RowIndex];

                cell.Value = 2;
                cell.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
                cell.ReadOnly = true;
            }
        }
    }
}
like image 129
Josh M. Avatar answered Oct 13 '22 00:10

Josh M.