Advertisement:

Skystone Software

http://www.SkystoneSoftware.com

Scott Waletzko's Blog
Updating ComboBox Items by Typing
Published: 11/3/2008
XMl / RSS

There was an interesting request over on the VBCity Forums asking how to update the selected item in a ComboBox by typing the change in the text area of the control. The problem is that the control changes selection of the drop-down (to -1) when you type something that isn't in the list. Working around that is as easy as keeping track of the last selected item in the SelectedIndexChanged event. Here's an example:

VB:
Public Class Form1 

    Private lastSelectedItemIndex As Integer = -1 

    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged 
        lastSelectedItemIndex = ComboBox1.SelectedIndex 
    End Sub 

    Private Sub ComboBox1_TextUpdate(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.TextUpdate 
        If (lastSelectedItemIndex > -1) Then 
            ' get cursor position... 
            Dim i As Integer = Me.ComboBox1.SelectionStart 
            ' update selected item... 
            ComboBox1.Items(lastSelectedItemIndex) = ComboBox1.Text 
            ' reset cursor position because it gets screwed up when you change selection... 
            Me.ComboBox1.SelectionStart = i + 1 
        End If 
    End Sub 

End Class 
C#:
public class Form1
{

	private int lastSelectedItemIndex = -1;

	private void ComboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
	{
		lastSelectedItemIndex = ComboBox1.SelectedIndex;
	}

	private void ComboBox1_TextUpdate(object sender, System.EventArgs e)
	{
		if (lastSelectedItemIndex > -1)
		{
			// get cursor position... 
			int i = this.ComboBox1.SelectionStart;
			// update selected item... 
			ComboBox1.Items[lastSelectedItemIndex] = ComboBox1.Text;
			// reset cursor position because it gets screwed up when you change selection... 
			this.ComboBox1.SelectionStart = i + 1;
		}
	}

}



Questions or Comments? .

VB to C# and C# to VB translation provided by Instant C# and Instant VB.