Click here to Skip to main content
15,899,025 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello

How can i re align my text on comboBox, I have a problem regarding this because when i press any keys on my keyboard it happens that the letters are type from right to left. Example "hello" this would appear as "olleh". Anyone has an idea on how can i solve this problem?

Here's my code on setting my comboBox items
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            this.comboBox1.Items.Clear();
            NpgsqlCommand com = new NpgsqlCommand("SELECT * FROM mem_profile where mem_id like '%" + comboBox1.Text + "%' or lname like '%" + comboBox1.Text + "%' or fname like '%" + comboBox1.Text + "%'", conDB.returnConnect());
            NpgsqlDataReader read = com.ExecuteReader();
            ArrayList sgGroup = new ArrayList();
            while (read.Read())
            {
                comboBox1.Items.Add(read[0].ToString() + "-" +read[1].ToString() + ", " + read[3].ToString()+ " "+ read[2].ToString());
            }
            comboBox1.DroppedDown = true;
        }


I dont why my text would appear from right to left when i type my keys on the keyboard. Any help would be appreciated. thanks
Posted
Updated 2-Mar-11 3:25am
v2
Comments
Yusuf 2-Mar-11 9:26am    
Moved your example code from answer to the question.

I think the problem lies in the fact that you are running the query in the keypress event, and as a result of this the cursor is always being reset to position 0 and the next character is being inserted at the start instead of at the end.

if you temporarily comment out your code does it work fine?

If you are trying to run a query while entering text, you should run a background worker process and pick off the text changed event rather than the key press event.

I think you need to rethink your strategy, search for examples of AutoCompletion.
 
Share this answer
 
It's because you are clearing the strings, which moves the caret to the start of the text.
C#
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
    comboBox1.Items.Clear();
    }
Will give the same effect.
To cure it try this:
C#
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
    int posn = comboBox1.SelectionStart;
    comboBox1.Items.Clear();
    comboBox1.SelectionStart = posn;
    }
It's not perfect - I haven't tried it with any selected text etc. - but that's the only way I know to get and set the caret position in a ComboBox
 
Share this answer
 
use that ?!

C#
public static string ReverseString(string s)
{
    char[] arr = s.ToCharArray();
    Array.Reverse(arr);
    return new string(arr);
}
 
Share this answer
 

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