I have a custom TextBox control (It is a custom one instead of a regular one to be able to have hint text on top of it), in which I have an AutoComplete that gets it's data from my DB using a DataSet like this
string[] postSource = aux.Tables[0].AsEnumerable().Select<System.Data.DataRow, String>(x => x.Field<String>("nm_industria")).ToArray();
var source = new AutoCompleteStringCollection();
source.AddRange(postSource);
txb_regClientData.AutoCompleteCustomSource = source;
txb_regClientData.AutoCompleteMode = AutoCompleteMode.Suggest;
txb_regClientData.AutoCompleteSource = AutoCompleteSource.CustomSource;
It gives me this result
Image if I type "João" it will give me the correct result, but if I type "Joao" it will not show up, from some reading on the matter I know that theres nothing in the AutoComplete to automatically ignore accentuation, so I will need to code it myself. My question is, where do I begin with this? My ideal solution would be to override something in the AutoComplete code of my custom control, I gave a read on the documentation for TextBox and couldn't find anything, so if anyone can show me the right direction so I can read and learn how to do this, would be highly appreciated.
There's still improvements to be done, but this code implements the solution for this, it "appends" a listBox to the textBox, there will be issues when multiple of these exist due to naming, but this should be a good starting point/reference for someone looking for something similar.
public class ExTextBox : TextBox
{
private bool alreadyRun = false;
ListBox suggestions = new ListBox();
int maxSize = 10;
string[] source;
public string Hint
public int MaxSuggestionBoxSize
{
get { return maxSize; }
set { maxSize = value; this.Invalidate(); }
}
protected override void OnCreateControl()
{
if (alreadyRun == false) // This is only supposed to be run once, but in some situations depending on the design of the main form,
{// this might need to be somewhere that gets called multiple times, this variable makes so this code is only run once even in those situations
suggestions.Name = "suggList_" + this.Name;
suggestions.Location = new Point(this.Location.X, (this.Location.Y + this.Size.Height));
suggestions.Size = new Size(this.Size.Width, this.Size.Height);
this.Parent.Controls.Add(suggestions);
this.Parent.Controls["suggList_" + this.Name].MouseDoubleClick += suggList_MouseDoubleClick;
this.Parent.Controls["suggList_" + this.Name].Hide();
alreadyRun = true;
}
base.OnCreateControl();
}
private void suggList_MouseDoubleClick(object sender, System.EventArgs e)
{
this.Text = this.Parent.Controls["suggList_" + this.Name].Text;
}
protected override void OnLeave(EventArgs e)
{
base.OnLeave(e);
if(source != null) // Makes sure this code is only executed when the suggestion box is being used, by checking the existance of the source
{
try
{
if (this.Parent.Controls["suggList_" + this.Name].Focused == false)
{
this.Parent.Controls["suggList_" + this.Name].Hide();
}
}
catch
{
}
}
}
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
AutoCompleteSmart();
}
public void AutoCompleteSmart()
{
if (source != null)
{
suggestions.Items.Clear();
if (this.Text != "")
{
foreach (string a in source)
{
if (RemoveDiacritics(a.ToLower()).Contains(RemoveDiacritics(this.Text.ToLower())))
{
suggestions.Items.Add(a);
}
}
this.Parent.Controls.Remove(suggestions);
if (suggestions.Items.Count < maxSize) // Optional code, defines a limit size for the suggestion box
{
suggestions.Size = new Size(this.Size.Width, ((suggestions.ItemHeight * suggestions.Items.Count) + suggestions.ItemHeight));
}
else
{
suggestions.Size = new Size(this.Size.Width, ((suggestions.ItemHeight * maxSize) + suggestions.ItemHeight));
}
this.Parent.Controls.Add(suggestions);
this.Parent.Controls["suggList_" + this.Name].BringToFront();
this.Parent.Controls["suggList_" + this.Name].Show();
}
else
{
this.Parent.Controls["suggList_" + this.Name].Hide();
}
}
}
public void AutoCompleteSmartSource(string[] _source)
{
source = _source;
}
private static string RemoveDiacritics(string text)
{
var normalizedString = text.Normalize(NormalizationForm.FormD);
var stringBuilder = new StringBuilder();
foreach (var c in normalizedString)
{
var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
if (unicodeCategory != UnicodeCategory.NonSpacingMark)
{
stringBuilder.Append(c);
}
}
return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}
}
Related
When I click on a checkbox I want the next checkbox information to be displayed on a new line, I know how to do this with "\r\n" however when unchecking the box and rechecking the box, it adds a new line above the text moving the original text down by 1 line. https://imgur.com/a/IHDDG85
I've tried "\r\n" and Environment.NewLine
private void chkHamburger_CheckedChanged(object sender, EventArgs e)
{
if (chkHamburger.Checked == true)
{
txtHamburger.Enabled = true;
txtHamburger.Text = "";
txtHamburger.Focus();
txtOrder.Text += ("Hamburger");
}
else
{
txtHamburger.Enabled = false;
txtHamburger.Text = "0";
}
if (chkHamburger.Checked == false)
{
txtOrder.Text = txtOrder.Text.Replace("Hamburger", "");
}
}
private void chkCheeseBurger_CheckedChanged(object sender, EventArgs e)
{
if (chkCheeseBurger.Checked == true)
{
txtCheeseBurger.Enabled = true;
txtCheeseBurger.Text = "";
txtCheeseBurger.Focus();
txtOrder.Text += ("Cheese Burger");
}
else
{
txtCheeseBurger.Enabled = false;
txtCheeseBurger.Text = "0";
}
if (chkCheeseBurger.Checked == false)
{
txtOrder.Text = txtOrder.Text.Replace("Cheese Burger", "");
}
}
I want the text of a checkbox to be displayed on a new line but when rechecking the box a whitespace should not appear above it.
I suggest you to use a List<string> where you add or remove your orders. Then it is easy to rebuild the txtOrder data with a single line of code using string.Join
List<string> orders = new List<string>();
private void chkHamburger_CheckedChanged(object sender, EventArgs e)
{
txtHamburger.Enabled = chkHamburger.Checked;
if (chkHamburger.Checked)
{
txtHamburger.Text = "";
txtHamburger.Focus();
orders.Add("Hamburger");
}
else
{
txtHamburger.Text = "0";
orders.Remove("Hamburger");
}
UpdateOrders();
}
private void chkCheeseBurger_CheckedChanged(object sender, EventArgs e)
{
txtCheeseBurger.Enabled = chkCheeseBurger.Checked;
if (chkCheeseBurger.Checked)
{
txtCheeseBurger.Text = "";
txtCheeseBurger.Focus();
orders.Add("Cheese Burger");
}
else
{
txtCheeseBurger.Text = "0";
orders.Remove("Cheese Burger");
}
UpdateOrders();
}
private void UpdateOrders()
{
txtOrders.Text = string.Join(Environment.NewLine, orders);
}
The best way to do this is to have a routine that builds the contents of the text independent of what just happened -- this you could use join or a loop to create the text contents.
Make this a function and call it when the check boxes change. The function loops over all your items and adds them to the output with the formatting and totals etc.
I am creating an application with an XML file called star.xml to store my data in a list view. I am very new to c# and programming and need any help
Basically, I want to be able to type in my search text box (called 'search') and for my list view (lstStar) to only show the matching records. I.e. typing in 'Audi' will only return those items.
any help will be much appreciated
jen
namespace StarinCar
{
public partial class MainWindow : Window
{
int hot = -2;
int Mildly_Moist = -2;
int Wet = -4;
int Very_Wet = -6;
private ObservableCollection<star> starData;
public MainWindow()
{
InitializeComponent();
starData = new ObservableCollection<star>();
lstStar.ItemsSource = starData;
try
{
XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<star>));
using (StreamReader rd = new StreamReader("star.xml"))
{
starData = xs.Deserialize(rd) as ObservableCollection<star>;
}
}
catch
{
}
lstStar.ItemsSource = starData;
lblAverage.Content = starData.Average(i => i.time).ToString();
lblFastest.Content = starData.Min(i => i.time).ToString();
lblSlowest.Content = starData.Max(i => i.time).ToString();
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
star newStar = new star();
newStar.firstName = txtName.Text;
newStar.time = int.Parse(txtTime.Text);
newStar.car = txtCar.Text;
newStar.track = txtTrack.Text;
starData.Add(newStar);
if (txtTrack.Text.Contains("Hot") || (txtTrack.Text.Contains("hot") == true))
{
newStar.time = int.Parse(txtTime.Text) + hot;
}
if (txtTrack.Text.Contains("Mildly Moist") || (txtTrack.Text.Contains("mildly moist")) == true)
{
newStar.time = int.Parse(txtTime.Text) + Mildly_Moist;
}
if (txtTrack.Text.Contains("Wet") || (txtTrack.Text.Contains("wet") == true))
{
newStar.time = int.Parse(txtTime.Text) + Wet;
}
if (txtTrack.Text.Contains("Very Wet") || (txtTrack.Text.Contains("very wet")) == true)
{
newStar.time = int.Parse(txtTime.Text) + Very_Wet;
}
}
private void Window_Closed(object sender, EventArgs e)
{
XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<star>));
using (StreamWriter wr = new StreamWriter("star.xml"))
{
xs.Serialize(wr, starData);
}
}
}
}
You could use ICollectionView. So you would have your "overall"
star collection 'starData'. But your listbox itemssource would be bound to something like this:
public ICollectionView FilteredStars
{
get
{
ICollectionView source = CollectionViewSource.GetDefaultView(starData);
source.Filter = new Predicate<object>(FilterStars);
return source;
}
}
the logic that does the filtering here:
private bool FilterStars(object item)
{
bool b = false;
star a = item as star;
if (a != null)
{
if (a.Name.Contains(searchBoxText)) //your filter logic here
{
b = true;
}
else if String.IsNullOrWhiteSpace(searchBoxText)
{
b = true;
}
}
return b;
}
Basically, you have your main collection, then some logic that filters your main collection to a filtered collection, and that's what you should set itemssource of your listbox to. This, so far, is assuming you are going to put some kind of property change into your search text box and probably then click a button, like "Search" to then tell the list to check and re-populate to match the search term.
This is how I filter in a similar application
public IEnumerable<string> PastEntries1
{
get
{
if(string.IsNullOrEmpty(textValue))
{
return FieldDefString.PastEntries;
}
else
{
return FieldDefString.PastEntries.Where(x => x.StartsWith(textValue, StringComparison.OrdinalIgnoreCase));
}
}
}
Here's my requirement. There is a public website which takes alphanumeric string as input and Retrieves data into a table element (via button click). The table element has couple of labels which gets populated with corresponding data. I need a tool/solution which can check if a particular string exists in the website's database. If so retrieve all the Ids of all the occurrences of that string. Looking at the "view source" of the website (No JavaScript used there), I noted the input element name and the button element name and with the help of existing samples I was able to get a working solution. Below is the code which works but I want to check if there is any better and faster approach. I know the below code has some issues like "infinite loop" issue and others. But I am basically looking at alternate solution which can work quickly for a million records.
namespace SearchWebSite
{
public partial class Form1 : Form
{
bool searched = false;
long i;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
i = 1;
WebBrowser browser = new WebBrowser();
string target = "http://www.SomePublicWebsite.com";
browser.Navigate(target);
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(XYZ);
}
private void XYZ(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser b = null;
if (searched == false)
{
b = (WebBrowser)sender;
b.Document.GetElementById("txtId").InnerText = "M" + i.ToString();
b.Document.GetElementById("btnSearch").InvokeMember("click");
searched = true;
}
if (b.ReadyState == WebBrowserReadyState.Complete)
{
if (b.Document.GetElementById("lblName") != null)
{
string IdNo = "M" + i.ToString();
string DateString = b.Document.GetElementById("lblDate").InnerHtml;
string NameString = b.Document.GetElementById("lblName").InnerHtml;
if (NameString != null && (NameString.Contains("XXXX") || NameString.Contains("xxxx")))
{
using (StreamWriter w = File.AppendText("log.txt"))
{
w.WriteLine("Id {0}, Date {1}, Name {2}", IdNo, DateString, NameString);
i = i + 1;
searched = false;
}
}
else
{
i = i + 1;
searched = false;
}
}
else
{
i = i + 1;
searched = false;
}
}
}
}
}
If the page after seach button clicked contains txtId and btnSearch controls than you can use this code snippet, this is not faster but the correct form I think.
public partial class Form1 : Form
{
bool searched = false;
long i = 1;
private string IdNo { get { return "M" + i.ToString(); } }
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
i = 1;
WebBrowser browser = new WebBrowser();
string target = "http://www.SomePublicWebsite.com";
browser.Navigate(target);
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(XYZ);
}
private void XYZ(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser b = (WebBrowser)sender;
if (b.ReadyState == WebBrowserReadyState. Complete)
{
if (searched == false)
{
DoSearch(b); return;
}
if (b.Document.GetElementById("lblName") != null)
{
string DateString = b.Document.GetElementById("lblDate").InnerHtml;
string NameString = b.Document.GetElementById("lblName").InnerHtml;
if (NameString != null && (NameString.Contains("XXXX") || NameString.Contains("xxxx")))
using (StreamWriter w = File.AppendText("log.txt"))
w.WriteLine("Id {0}, Date {1}, Name {2}", IdNo, DateString, NameString);
}
i++;
DoSearch(b);
}
}
private void DoSearch(WebBrowser wb)
{
wb.Document.GetElementById("txtId").InnerText = IdNo;
wb.Document.GetElementById("btnSearch").InvokeMember("click");
searched = true;
}
}
I have 2 parameters defined in SharePoint web part project, meant to be passed into Application_Startup() in a Silverlight application when a user selects from 2 combo boxes (browsable properties). Somehow the Silverlight control does not render when i load it on the SharePoint site. With 1 parameter passed in, the control displays without error. Any ideas? Syntax? Examples?
App.xaml.cs:
private void Application_Startup(object sender, StartupEventArgs e)
{
//testing
string _setArticles = null;
string _setLength = null;
if (e.InitParams != null && e.InitParams.Count >= 1)
{
_setArticles = e.InitParams["_setArticles"];
_setLength = e.InitParams["_setLength"];
}
this.RootVisual = new Page(_setArticles, _setLength);
}
Page.xaml.cs:
public Page(string _setArticles, string _setLength)
{
InitializeComponent();
//(number of items to display on load)
if (!string.IsNullOrEmpty(_setArticles) && !string.IsNullOrEmpty(_setLength) )
{
if (_setArticles.Equals("_1_article"))
retrieveOneListboxItemStaffNews();
GetData3();
if (_setArticles.Equals("_2_articles"))
retrieveTwoListboxItemStaffNews();
GetData3();
if (_setArticles.Equals("_3_articles"))
retrieveThreeListboxItemStaffNews();
GetData3();
//testing
//send value to method 'fullNameControl_Loaded' (summary length of each ListBox item)
if (_setLength.Equals("_3_lines"))
m_textBlock.MaxHeight = 40;
if (_setLength.Equals("_4_lines"))
m_textBlock.MaxHeight = 50;
if (_setLength.Equals("_5_lines"))
m_textBlock.MaxHeight = 65;
}
}
SilverlightSecondWebPart.cs:
protected override void CreateChildControls()
{
base.CreateChildControls();
//silverlight control
silverlightControl = new Silverlight();
silverlightControl.ID = "News";
silverlightControl.Source = "/ClientBin/News.xap";
silverlightControl.Width = new System.Web.UI.WebControls.Unit(800);
silverlightControl.Height = new System.Web.UI.WebControls.Unit(550);
//testing
string parameters = "_setArticles=" + _myEnum + ", " + "_setLength=" + _myEnum2;
silverlightControl.InitParameters = parameters;
silverlightControl.MinimumVersion = "2.0";
Controls.Add(silverlightControl);
}
Anyway use
if (_setArticles.Equals("_1_article"))
{
retrieveOneListboxItemStaffNews();
GetData3();
}
if (_setArticles.Equals("_2_articles"))
{
retrieveTwoListboxItemStaffNews();
GetData3();
}
if (_setArticles.Equals("_3_articles"))
{
retrieveThreeListboxItemStaffNews();
GetData3();
}
otherwise GetData3() will be called anyway, 3 times each time.
I am trying to add an autocomplete feature to a textbox, the results are coming from a database. They come in the format of
[001] Last, First Middle
Currently you must type [001]... to get the entries to show. So the problem is that I want it to complete even if I type the firstname first. So if an entry was
[001] Smith, John D
if I started typing John then this entry should show up in the results for the auto complete.
Currently the code looks something like
AutoCompleteStringCollection acsc = new AutoCompleteStringCollection();
txtBox1.AutoCompleteCustomSource = acsc;
txtBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
txtBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
....
if (results.Rows.Count > 0)
for (int i = 0; i < results.Rows.Count && i < 10; i++)
{
row = results.Rows[i];
acsc.Add(row["Details"].ToString());
}
}
results is a dataset containing the query results
The query is a simple search query using the like statement. The correct results are returned if we do not use the autocomplete and just toss the results into an array.
Any advice?
EDIT:
Here is the query that returns the results
SELECT Name from view_customers where Details LIKE '{0}'
With {0} being the placeholder for the searched string.
The existing AutoComplete functionality only supports searching by prefix. There doesn't seem to be any decent way to override the behavior.
Some people have implemented their own autocomplete functions by overriding the OnTextChanged event. That's probably your best bet.
For example, you can add a ListBox just below the TextBox and set its default visibility to false. Then you can use the OnTextChanged event of the TextBox and the SelectedIndexChanged event of the ListBox to display and select items.
This seems to work pretty well as a rudimentary example:
public Form1()
{
InitializeComponent();
acsc = new AutoCompleteStringCollection();
textBox1.AutoCompleteCustomSource = acsc;
textBox1.AutoCompleteMode = AutoCompleteMode.None;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
private void button1_Click(object sender, EventArgs e)
{
acsc.Add("[001] some kind of item");
acsc.Add("[002] some other item");
acsc.Add("[003] an orange");
acsc.Add("[004] i like pickles");
}
void textBox1_TextChanged(object sender, System.EventArgs e)
{
listBox1.Items.Clear();
if (textBox1.Text.Length == 0)
{
hideResults();
return;
}
foreach (String s in textBox1.AutoCompleteCustomSource)
{
if (s.Contains(textBox1.Text))
{
Console.WriteLine("Found text in: " + s);
listBox1.Items.Add(s);
listBox1.Visible = true;
}
}
}
void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
textBox1.Text = listBox1.Items[listBox1.SelectedIndex].ToString();
hideResults();
}
void listBox1_LostFocus(object sender, System.EventArgs e)
{
hideResults();
}
void hideResults()
{
listBox1.Visible = false;
}
There's a lot more you could do without too much effort: append text to the text box, capture additional keyboard commands, and so forth.
If you decide to use a query that is based on user input make sure you use SqlParameters to avoid SQL Injection attacks
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.CommandText = "SELECT Name from view_customers where Details LIKE '%" + #SearchParam + "%'";
sqlCommand.Parameters.AddWithValue("#SearchParam", searchParam);
Here's an implementation that inherits the ComboBox control class, rather than replacing the whole combo-box with a new control. It displays its own drop-down when you type in the text box, but clicking to show the drop-list is handled as before (i.e. not with this code). As such you get that proper native control and look.
Please use it, modify it and edit the answer if you would like to improve it!
class ComboListMatcher : ComboBox, IMessageFilter
{
private Control ComboParentForm; // Or use type "Form"
private ListBox listBoxChild;
private int IgnoreTextChange;
private bool MsgFilterActive = false;
public ComboListMatcher()
{
// Set up all the events we need to handle
TextChanged += ComboListMatcher_TextChanged;
SelectionChangeCommitted += ComboListMatcher_SelectionChangeCommitted;
LostFocus += ComboListMatcher_LostFocus;
MouseDown += ComboListMatcher_MouseDown;
HandleDestroyed += ComboListMatcher_HandleDestroyed;
}
void ComboListMatcher_HandleDestroyed(object sender, EventArgs e)
{
if (MsgFilterActive)
Application.RemoveMessageFilter(this);
}
~ComboListMatcher()
{
}
private void ComboListMatcher_MouseDown(object sender, MouseEventArgs e)
{
HideTheList();
}
void ComboListMatcher_LostFocus(object sender, EventArgs e)
{
if (listBoxChild != null && !listBoxChild.Focused)
HideTheList();
}
void ComboListMatcher_SelectionChangeCommitted(object sender, EventArgs e)
{
IgnoreTextChange++;
}
void InitListControl()
{
if (listBoxChild == null)
{
// Find parent - or keep going up until you find the parent form
ComboParentForm = this.Parent;
if (ComboParentForm != null)
{
// Setup a messaage filter so we can listen to the keyboard
if (!MsgFilterActive)
{
Application.AddMessageFilter(this);
MsgFilterActive = true;
}
listBoxChild = listBoxChild = new ListBox();
listBoxChild.Visible = false;
listBoxChild.Click += listBox1_Click;
ComboParentForm.Controls.Add(listBoxChild);
ComboParentForm.Controls.SetChildIndex(listBoxChild, 0); // Put it at the front
}
}
}
void ComboListMatcher_TextChanged(object sender, EventArgs e)
{
if (IgnoreTextChange > 0)
{
IgnoreTextChange = 0;
return;
}
InitListControl();
if (listBoxChild == null)
return;
string SearchText = this.Text;
listBoxChild.Items.Clear();
// Don't show the list when nothing has been typed
if (!string.IsNullOrEmpty(SearchText))
{
foreach (string Item in this.Items)
{
if (Item != null && Item.Contains(SearchText, StringComparison.CurrentCultureIgnoreCase))
listBoxChild.Items.Add(Item);
}
}
if (listBoxChild.Items.Count > 0)
{
Point PutItHere = new Point(this.Left, this.Bottom);
Control TheControlToMove = this;
PutItHere = this.Parent.PointToScreen(PutItHere);
TheControlToMove = listBoxChild;
PutItHere = ComboParentForm.PointToClient(PutItHere);
TheControlToMove.Show();
TheControlToMove.Left = PutItHere.X;
TheControlToMove.Top = PutItHere.Y;
TheControlToMove.Width = this.Width;
int TotalItemHeight = listBoxChild.ItemHeight * (listBoxChild.Items.Count + 1);
TheControlToMove.Height = Math.Min(ComboParentForm.ClientSize.Height - TheControlToMove.Top, TotalItemHeight);
}
else
HideTheList();
}
/// <summary>
/// Copy the selection from the list-box into the combo box
/// </summary>
private void CopySelection()
{
if (listBoxChild.SelectedItem != null)
{
this.SelectedItem = listBoxChild.SelectedItem;
HideTheList();
this.SelectAll();
}
}
private void listBox1_Click(object sender, EventArgs e)
{
var ThisList = sender as ListBox;
if (ThisList != null)
{
// Copy selection to the combo box
CopySelection();
}
}
private void HideTheList()
{
if (listBoxChild != null)
listBoxChild.Hide();
}
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == 0x201) // Mouse click: WM_LBUTTONDOWN
{
var Pos = new Point((int)(m.LParam.ToInt32() & 0xFFFF), (int)(m.LParam.ToInt32() >> 16));
var Ctrl = Control.FromHandle(m.HWnd);
if (Ctrl != null)
{
// Convert the point into our parent control's coordinates ...
Pos = ComboParentForm.PointToClient(Ctrl.PointToScreen(Pos));
// ... because we need to hide the list if user clicks on something other than the list-box
if (ComboParentForm != null)
{
if (listBoxChild != null &&
(Pos.X < listBoxChild.Left || Pos.X > listBoxChild.Right || Pos.Y < listBoxChild.Top || Pos.Y > listBoxChild.Bottom))
{
this.HideTheList();
}
}
}
}
else if (m.Msg == 0x100) // WM_KEYDOWN
{
if (listBoxChild != null && listBoxChild.Visible)
{
switch (m.WParam.ToInt32())
{
case 0x1B: // Escape key
this.HideTheList();
return true;
case 0x26: // up key
case 0x28: // right key
// Change selection
int NewIx = listBoxChild.SelectedIndex + ((m.WParam.ToInt32() == 0x26) ? -1 : 1);
// Keep the index valid!
if (NewIx >= 0 && NewIx < listBoxChild.Items.Count)
listBoxChild.SelectedIndex = NewIx;
return true;
case 0x0D: // return (use the currently selected item)
CopySelection();
return true;
}
}
}
return false;
}
}
THIS WILL GIVE YOU THE AUTOCOMPLETE BEHAVIOR YOU ARE LOOKING FOR.
The attached example is a complete working form, Just needs your data source, and bound column names.
using System;
using System.Data;
using System.Windows.Forms;
public partial class frmTestAutocomplete : Form
{
private DataTable maoCompleteList; //the data table from your data source
private string msDisplayCol = "name"; //displayed text
private string msIDcol = "id"; //ID or primary key
public frmTestAutocomplete(DataTable aoCompleteList, string sDisplayCol, string sIDcol)
{
InitializeComponent();
maoCompleteList = aoCompleteList
maoCompleteList.CaseSensitive = false; //turn off case sensitivity for searching
msDisplayCol = sDisplayCol;
msIDcol = sIDcol;
}
private void frmTestAutocomplete_Load(object sender, EventArgs e)
{
testCombo.DisplayMember = msDisplayCol;
testCombo.ValueMember = msIDcol;
testCombo.DataSource = maoCompleteList;
testCombo.SelectedIndexChanged += testCombo_SelectedIndexChanged;
testCombo.KeyUp += testCombo_KeyUp;
}
private void testCombo_KeyUp(object sender, KeyEventArgs e)
{
//use keyUp event, as text changed traps too many other evengts.
ComboBox oBox = (ComboBox)sender;
string sBoxText = oBox.Text;
DataRow[] oFilteredRows = maoCompleteList.Select(MC_DISPLAY_COL + " Like '%" + sBoxText + "%'");
DataTable oFilteredDT = oFilteredRows.Length > 0
? oFilteredRows.CopyToDataTable()
: maoCompleteList;
//NOW THAT WE HAVE OUR FILTERED LIST, WE NEED TO RE-BIND IT WIHOUT CHANGING THE TEXT IN THE ComboBox.
//1).UNREGISTER THE SELECTED EVENT BEFORE RE-BINDING, b/c IT TRIGGERS ON BIND.
testCombo.SelectedIndexChanged -= testCombo_SelectedIndexChanged; //don't select on typing.
oBox.DataSource = oFilteredDT; //2).rebind to filtered list.
testCombo.SelectedIndexChanged += testCombo_SelectedIndexChanged;
//3).show the user the new filtered list.
oBox.DroppedDown = true; //do this before repainting the text, as it changes the dropdown text.
//4).binding data source erases text, so now we need to put the user's text back,
oBox.Text = sBoxText;
oBox.SelectionStart = sBoxText.Length; //5). need to put the user's cursor back where it was.
}
private void testCombo_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox oBox = (ComboBox)sender;
if (oBox.SelectedValue != null)
{
MessageBox.Show(string.Format(#"Item #{0} was selected.", oBox.SelectedValue));
}
}
}
//=====================================================================================================
// code from frmTestAutocomplete.Designer.cs
//=====================================================================================================
partial class frmTestAutocomplete
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.testCombo = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
//
// testCombo
//
this.testCombo.FormattingEnabled = true;
this.testCombo.Location = new System.Drawing.Point(27, 51);
this.testCombo.Name = "testCombo";
this.testCombo.Size = new System.Drawing.Size(224, 21);
this.testCombo.TabIndex = 0;
//
// frmTestAutocomplete
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.Add(this.testCombo);
this.Name = "frmTestAutocomplete";
this.Text = "frmTestAutocomplete";
this.Load += new System.EventHandler(this.frmTestAutocomplete_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ComboBox testCombo;
}
If you're running that query (with {0} being replaced by the string entered), you might need:
SELECT Name from view_customers where Details LIKE '%{0}%'
LIKE still needs the % character... And yes, you should use parameters rather than trusting the user's input :)
Also, you seem to be returning the Name column, but querying on the Details column. So if someone types in "John Smith", if that's not in the Details column you won't get what you want back.
Two methods were successful in the autoComplete textBox control with SQL:
but you should do the following:
a- create new project
b- add Component class to project and delete component1.designer "according to the name you give to component class"
c- download "Download sample - 144.82 KB"
and open it and open AutoCompleteTextbox class from AutoCompleteTextbox.cs
d- select all as illustrated in the image and copy it to current component class
http://i.stack.imgur.com/oSqCa.png
e- Final - run project and stop to view new AutoCompleteTextbox in toolBox.
Now you can add the following two method that you can use SQL with them
1- in Form_Load
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"server=.;database=My_dataBase;integrated security=true");
SqlDataAdapter da = new SqlDataAdapter(#"SELECT [MyColumn] FROM [my_table]", cn);
DataTable dt = new DataTable();
da.Fill(dt);
List<string> myList = new List<string>();
foreach (DataRow row in dt.Rows)
{
myList.Add((string)row[0]);
}
autoCompleteTextbox1.AutoCompleteList = myList;
}
2- in TextChanged Event
private void autoCompleteTextbox_TextChanged(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"server=.;database=My_dataBase;integrated security=true");
SqlDataAdapter da = new SqlDataAdapter(#"SELECT [MyColumn] FROM [my_table]", cn);
DataTable dt = new DataTable();
da.Fill(dt);
List<string> myList = new List<string>();
foreach (DataRow row in dt.Rows)
{
myList.Add((string)row[0]);
}
autoCompleteTextbox2.AutoCompleteList = myList;
}