Sé que este es un tema antiguo, pero traté muy duro de encontrar una solución para el filtrado autocompletado de C# y no pude encontrar ninguno, así que ideé mi propia manera simple y fácil, así que solo la compartiré para aquellos que pueden pensar que es útil y que quieren usar en sus proyectos. No utiliza las funciones de autocompletar del control. Lo que hace simplemente es obtener el texto ingresado desde el cuadro combinado, buscarlo en la fuente y luego mostrar solo los que coincidan desde el origen como la nueva fuente del cuadro combinado. Lo implementé en el combobox 'KeyUp
evento.
Digamos que (en realidad esto es lo que hago para casi todos los casos cuando quiero autocompletar) tenemos un DataTable
llamado globalmente dt_source para ser el origen del combobox y tiene dos columnas: id (int) y nombre (cuerda).
DataTable dt_source = new DataTable("table");
dt_source.Columns.Add("id", typeof(int));
dt_source.Columns.Add("name", typeof(string));
Y esto es lo que mi método KeyUp se parece a:
private void cmb_box_KeyUp(object sender, KeyEventArgs e)
{
string srch = cmb_box.Text;
string srch_str = "ABackCDeleteEFGHIJKLMNOPQRSpaceTUVWXYZD1D2D3D4D5D6D7D8D9D0";
if (srch_str.IndexOf(e.KeyCode.ToString()) >= 0)
{
cmb_box.DisplayMember = "name"; // we want name list in the datatable to be shown
cmb_box.ValueMember = "id"; // we want id field in the datatable to be the value
DataView dv_source = new DataView(dt_source); // make a DataView from DataTable so ...
dv_source.RowFilter = "name LIKE '%"+ srch +"%'"; // ... we can filter it
cmb_box.DataSource = dv_source; // append this DataView as a new source to the combobox
/* The 3 lines below is the tricky part. If you repopulate a combobox, the first
item in it will be automatically selected so let's unselect it*/
cmb_box.SelectedIndex = -1; // unselection
/* Again when a combobox repopulated the text region will be reset but we have the
srch variable to rewrite what's written before */
cmb_box.Text = srch;
/* And since we're rewriting the text region let's make the cursor appear at the
end of the text - assuming 100 chars is enough*/
cmb_box.Select(100,0);
cmb_box.DroppedDown = true; // Showing the dropdownlist
}
}
formularios web? Winforms? MVC? WPF? –
necesito en winforms C# esto – jozi
¿Qué versión de framework estás usando? ¿Accedes a LINQ? – invert