C # winforms combobox dynamic autocomplete
Mój problem jest podobny do tego: Jak mogę dynamicznie zmieniać automatyczne wypełnianie wpisów w C # combobox lub textbox? Ale nadal nie znajduję rozwiązania.
Problem krótko:
Mam ComboBox
i dużą liczbę rekordów do pokazania w nim. Kiedy użytkownik zaczyna pisać chcę załadować rekordy, które zaczynają się od tekstu wejściowego i oferują użytkownikowi autouzupełnianie.
Jak opisano w temacie powyżej nie mogę załadować ich na сomboBox_TextChanged
ponieważ zawsze nadpisuję poprzednie wyniki i nigdy ich nie widuję.
Czy Mogę to zaimplementować używając tylko ComboBox
? (nie TextBox
lub ListBox
)
Używam tych ustawień:
сomboBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
сomboBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
8 answers
Ostatnio też spotykam się z tego typu wymaganiami.Ustawiłem poniższe właściwości bez pisania kodu, który działa.zobacz, czy to ci pomoże.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-04 10:04:07
Oto moje ostateczne rozwiązanie. Działa dobrze z dużą ilością danych. Używam Timer
, aby upewnić się, że użytkownik chce znaleźć bieżącą wartość. Wygląda na złożony, ale nie jest.
Podziękowania dla Maxa Lambertini za pomysł.
private bool _canUpdate = true;
private bool _needUpdate = false;
//If text has been changed then start timer
//If the user doesn't change text while the timer runs then start search
private void combobox1_TextChanged(object sender, EventArgs e)
{
if (_needUpdate)
{
if (_canUpdate)
{
_canUpdate = false;
UpdateData();
}
else
{
RestartTimer();
}
}
}
private void UpdateData()
{
if (combobox1.Text.Length > 1)
{
List<string> searchData = Search.GetData(combobox1.Text);
HandleTextChanged(searchData);
}
}
//If an item was selected don't start new search
private void combobox1_SelectedIndexChanged(object sender, EventArgs e)
{
_needUpdate = false;
}
//Update data only when the user (not program) change something
private void combobox1_TextUpdate(object sender, EventArgs e)
{
_needUpdate = true;
}
//While timer is running don't start search
//timer1.Interval = 1500;
private void RestartTimer()
{
timer1.Stop();
_canUpdate = false;
timer1.Start();
}
//Update data when timer stops
private void timer1_Tick(object sender, EventArgs e)
{
_canUpdate = true;
timer1.Stop();
UpdateData();
}
//Update combobox with new data
private void HandleTextChanged(List<string> dataSource)
{
var text = combobox1.Text;
if (dataSource.Count() > 0)
{
combobox1.DataSource = dataSource;
var sText = combobox1.Items[0].ToString();
combobox1.SelectionStart = text.Length;
combobox1.SelectionLength = sText.Length - text.Length;
combobox1.DroppedDown = true;
return;
}
else
{
combobox1.DroppedDown = false;
combobox1.SelectionStart = text.Length;
}
}
To rozwiązanie nie jest zbyt fajne. Więc jeśli ktoś ma inne rozwiązanie Proszę podzielić się nim ze mną.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-23 13:49:48
Tak, na pewno możesz... ale to wymaga trochę pracy, aby to działa bezproblemowo. To jakiś kod, który wymyśliłem. Należy pamiętać, że to nie używać funkcji auto-complete combobox, i może być dość powolny, jeśli używasz go do przesiewania przez wiele przedmiotów...
string[] data = new string[] {
"Absecon","Abstracta","Abundantia","Academia","Acadiau","Acamas",
"Ackerman","Ackley","Ackworth","Acomita","Aconcagua","Acton","Acushnet",
"Acworth","Ada","Ada","Adair","Adairs","Adair","Adak","Adalberta","Adamkrafft",
"Adams"
};
public Form1()
{
InitializeComponent();
}
private void comboBox1_TextChanged(object sender, EventArgs e)
{
HandleTextChanged();
}
private void HandleTextChanged()
{
var txt = comboBox1.Text;
var list = from d in data
where d.ToUpper().StartsWith(comboBox1.Text.ToUpper())
select d;
if (list.Count() > 0)
{
comboBox1.DataSource = list.ToList();
//comboBox1.SelectedIndex = 0;
var sText = comboBox1.Items[0].ToString();
comboBox1.SelectionStart = txt.Length;
comboBox1.SelectionLength = sText.Length - txt.Length;
comboBox1.DroppedDown = true;
return;
}
else
{
comboBox1.DroppedDown = false;
comboBox1.SelectionStart = txt.Length;
}
}
private void comboBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
int sStart = comboBox1.SelectionStart;
if (sStart > 0)
{
sStart--;
if (sStart == 0)
{
comboBox1.Text = "";
}
else
{
comboBox1.Text = comboBox1.Text.Substring(0, sStart);
}
}
e.Handled = true;
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-05 11:27:19
Napisałem coś takiego ....
private void frmMain_Load(object sender, EventArgs e)
{
cboFromCurrency.Items.Clear();
cboComboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
cboComboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
// Load data in comboBox => cboComboBox1.DataSource = .....
// Other things
}
private void cboComboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
cboComboBox1.DroppedDown = false;
}
That ' s all (Y)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-05 15:55:19
ODPOWIEDŹ Maxa Lambertiniego okazała się bardzo pomocna, ale zmodyfikowałem jego metodę HandleTextChanged jako taką:
//I like min length set to 3, to not give too many options
//after the first character or two the user types
public Int32 AutoCompleteMinLength {get; set;}
private void HandleTextChanged() {
var txt = comboBox.Text;
if (txt.Length < AutoCompleteMinLength)
return;
//The GetMatches method can be whatever you need to filter
//table rows or some other data source based on the typed text.
var matches = GetMatches(comboBox.Text.ToUpper());
if (matches.Count() > 0) {
//The inside of this if block has been changed to allow
//users to continue typing after the auto-complete results
//are found.
comboBox.Items.Clear();
comboBox.Items.AddRange(matches);
comboBox.DroppedDown = true;
Cursor.Current = Cursors.Default;
comboBox.Select(txt.Length, 0);
return;
}
else {
comboBox.DroppedDown = false;
comboBox.SelectionStart = txt.Length;
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-23 15:15:46
Ten kod jest zapisywany na Twoim formularzu. Wyświetla całą trasę w bazie danych, gdy użytkownik wpisuje literę w polu combo. Ten kod automatycznie sugeruje i dołącza odpowiedni wybór według potrzeb użytkownika.
con.Open();
cmd = new SqlCommand("SELECT DISTINCT Tour FROM DetailsTB", con);
SqlDataReader sdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(sdr);
combo_search2.DisplayMember = "Tour";
combo_search2.DroppedDown = true;
List<string> list = new List<string>();
foreach (DataRow row in dt.Rows)
{
list.Add(row.Field<string>("Tour"));
}
this.combo_search2.Items.AddRange(list.ToArray<string>());
combo_search2.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
combo_search2.AutoCompleteSource = AutoCompleteSource.ListItems;
con.Close();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-10 04:43:33
W poprzednich odpowiedziach są wady. Oferuje własną wersję z zaznaczeniem na rozwijanej liście pożądanego elementu:
private ConnectSqlForm()
{
InitializeComponent();
cmbDatabases.TextChanged += UpdateAutoCompleteComboBox;
cmbDatabases.KeyDown += AutoCompleteComboBoxKeyPress;
}
private void UpdateAutoCompleteComboBox(object sender, EventArgs e)
{
var comboBox = sender as ComboBox;
if(comboBox == null)
return;
string txt = comboBox.Text;
string foundItem = String.Empty;
foreach(string item in comboBox.Items)
if (!String.IsNullOrEmpty(txt) && item.ToLower().StartsWith(txt.ToLower()))
{
foundItem = item;
break;
}
if (!String.IsNullOrEmpty(foundItem))
{
if (String.IsNullOrEmpty(txt) || !txt.Equals(foundItem))
{
comboBox.TextChanged -= UpdateAutoCompleteComboBox;
comboBox.Text = foundItem;
comboBox.DroppedDown = true;
Cursor.Current = Cursors.Default;
comboBox.TextChanged += UpdateAutoCompleteComboBox;
}
comboBox.SelectionStart = txt.Length;
comboBox.SelectionLength = foundItem.Length - txt.Length;
}
else
comboBox.DroppedDown = false;
}
private void AutoCompleteComboBoxKeyPress(object sender, KeyEventArgs e)
{
var comboBox = sender as ComboBox;
if (comboBox != null && comboBox.DroppedDown)
{
switch (e.KeyCode)
{
case Keys.Back:
int sStart = comboBox.SelectionStart;
if (sStart > 0)
{
sStart--;
comboBox.Text = sStart == 0 ? "" : comboBox.Text.Substring(0, sStart);
}
e.SuppressKeyPress = true;
break;
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-12 09:26:24
using (var client = new UserServicesClient())
{
var list = new AutoCompleteStringCollection();
list.AddRange(client.ListNames(query).ToArray());
comboBoxName.AutoCompleteCustomSource = list;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-12 21:41:45