Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Simplest Way to Make Readonly ComboBox

2.67/5 (6 votes)
5 May 2009CPOL1 min read 39.5K   436  
Readonly ComboBox
tt.jpg

Introduction

I was looking on this site to find a way to make a read only ComboBox. There is more than one article to do that, but some of them are very huge and some do not work, especially against Delete button. That made me look for a solution for this problem. Finally, I found a very simple way to do that. The idea is to control the input keys.

There are two types of input keys:

  1. Normal keys (letters, numbers…)
  2. Control keys (delete, left…)

Using the Code

The simplest way to control a Normal key is by converting it to null before using it. To do that, we can handle the input keys for the combo box by using: KeyPress event (or simply disable this event), see the code. And now, a slightly harder step, controlling the control keys. First, let us watch the key pressed before doing its work, if it is a control key, we will not pass it to do as an underline control. To do that, the best way is to use the KeyDown Event. 

My ComboBox allows: Cntr+C(copy) and arrows effects. Finally we will create contextMenuStrip to allow only copy, as shown below:

C#
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = true;
}

private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyData == (Keys)Shortcut.CtrlC)
    {
         Clipboard.SetData(DataFormats.Text, comboBox1.SelectedText);
    }
    else if (e.KeyData == Keys.Left || e.KeyData == Keys.Right || 
		e.KeyData == Keys.Up || e.KeyData == Keys.Down) { }
    else
    {
         e.Handled = true;
    }
}

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
     Clipboard.SetData(DataFormats.Text, comboBox1.SelectedText );
}

And now you can improve your code as you wish. You can also add your own features. If you have any questions, please post them.

Hints

  1. You can change the style of combobox to list style. (See the code.) But, doing that may remove some features (copy, select text, … ), your choice depends on your application.
    C#
    private void Form1_Load(object sender, EventArgs e) 
    {  
        comboBox2.DropDownStyle = ComboBoxStyle.DropDownList; 	// thanks for 
    							// your commands 
    }
  2. If someone wants to delete contextMenuStrip effect "Mouse right-click", you can add the following:
    C#
    private void Form1_Load(object sender, EventArgs e)
    { 
        comboBox3.ContextMenu = new ContextMenu();
    }

License

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