Based on gender, I want to load certain criteria.
For example, if I type 0 in a textbox, I want to load Mr., Dr. , etc..
If I type 1, I want to load Ms, Mrs, Miss, Dr. etc...
How can I do so?
Gender is typed in a textbox, and I want the combo box to load what I specified above.
Thank you.
This is just Sudo code there must be typo or Syntax error but you need to do something as below :
List<string> strMale = new List<string>{"Mr.", "Dr. "};
List<string> strFMale = new List<string>{"Mrs.", "Miss"};
//make use of Textbox Change Event
public void Text1_TextChanged(object sender, EventArgs e)
{
Combo1.Items.Clear();
//Bind the values using the text box input value
if(Text1.Text=="0")
{
Combo1.DataSource = strMale ;
}
else if(Text1.Text=="1")
{
Combo1.DataSource = strFMale ;
}
Combo1.SelectedIndex = 0;
}
You have to handle event ValueChanged (the name of the event depends on platform you're working with) and depending on value typed change source of your combobox
Try the following Code Use can use comboBox.Items.Insert or comboBox.Items.Add for inserting new items into a combobox.
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (textBox2.Text == "0")
{
if (comboBox1.Items.Count > 0)
comboBox1.Items.Clear();
comboBox1.Items.Insert(0,"Mr");
comboBox1.Items.Insert(1, "Dr");
}
else if (textBox2.Text == "1")
{
if (comboBox1.Items.Count > 0)
comboBox1.Items.Clear();
comboBox1.Items.Add("Ms");
comboBox1.Items.Add("Mrs");
comboBox1.Items.Add("Miss");
}
}
Related
I would like to have a column of ComboBoxes in a DataGridView, which allows the user to freely input some text, which is collected in the dropdown menus, so that entering the same text in the next box is faster. I'd prefer not to use DataGridViewComboBoxColumn, unless I really have to.
The following code nearly does the job but has these issues:
After entering some new text and hitting return, the newly entered text is immediately replaced with the old value
But the new text is successfully added to the dropdown menus of all of the comboboxes
when I select this newly added text in one of the boxes, I get DataGridView-Exceptions complaining about an invalid value.
It seems the boxes somehow have for validation purposes a copy of the datasource which doesn't get updated?
public partial class Form1 : Form
{
List<string> data = new List<string>(); // shared data source for all ComboBoxes
private void checkData(string s) // check wether s in the list, add it if not, keep things sorted
{
if (data.Contains(s))
return;
data.Add(s);
data.Sort();
}
private void addCell(string s) // add a new cell to the grid
{
checkData(s);
DataGridViewComboBoxCell c = new DataGridViewComboBoxCell();
c.DataSource = data;
c.Value = s;
int i = theGrid.Rows.Add();
theGrid.Rows[i].Cells[0] = c;
}
public Form1()
{
InitializeComponent();
theGrid.ColumnCount = 1;
addCell("Foo");
addCell("Bar");
}
// handler to enable the user to enter free text
private void theGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox cb = e.Control as ComboBox;
if (cb != null)
cb.DropDownStyle = ComboBoxStyle.DropDown;
}
// handler which adds the entered text to the data source
private void theGrid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.RowIndex < 0 || e.ColumnIndex < 0)
return;
checkData(e.FormattedValue.ToString());
}
}
After some tests, I am guessing that the individual combo boxes are not getting updated as you think they are. It appears that in the checkData method, that the data is updated with a new s. This will visually update the combo box cell, however the DataSource for each of the combos needs to be updated. Hence the DataError exception when the new added value is selected.
Considering that each combo box cell is “independent” and not part of a DataGridViewComboBoxColumn… then a loop through all the rows is necessary to update each combo box cell. I am not sure why a DataGridViewComboBoxColumn would not be used here.
private void checkData(string s) // check wether s in the list, add it if not, keep things sorted
{
if (data.Contains(s))
return;
data.Add(s);
data.Sort();
// now because each cell is independent... we have to update each data source!
UpdateCombos();
}
private void UpdateCombos() {
foreach (DataGridViewRow row in theGrid.Rows) {
if ((!row.IsNewRow) && (row.Cells[0].Value != null)) {
string currentValue = row.Cells[0].Value.ToString();
DataGridViewComboBoxCell c = new DataGridViewComboBoxCell();
c.Value = currentValue;
c.DataSource = data;
row.Cells[0] = c;
}
}
}
Using the posted code, A call to UpdateCombos is added to the checkData method. This method as expected loops through all the rows in the grid and replaces each combo box with the updated data. I will not disagree that it may be prudent to replace the data source, however I would use a combo box column, which the code below does. With this change, the UpdateCombos is not needed and simply update the combo box column.
The DataGridViewComboBoxColumn is exposed since the data source is updated frequently.
private List<string> comboData;
private DataGridViewComboBoxColumn comboColumn;
private void Form2_Load(object sender, EventArgs e) {
comboData = new List<string>();
comboData.Add("Foo");
comboData.Add("Bar");
comboColumn = new DataGridViewComboBoxColumn();
comboColumn.DataSource = comboData;
theGrid2.Columns.Add(comboColumn);
theGrid2.RowCount = 3;
}
private void checkData2(string s) {
if (!comboData.Contains(s)) {
comboData.Add(s);
comboData.Sort();
comboColumn.DataSource = null;
comboColumn.DataSource = comboData;
}
}
Hope that helps
I want to filter the items that I added to my Listview, using my textbox_TextChanged Can you please show me the Codes, I am using Visual Studio 2013. tia
e.g.
First I am adding a Destination/Regularfare/Discountedfare/Baggagefare to my ListView. and my problem is Searching I want to search the Destinations using a TextBox.
There are no Codes inside my TextBox Search. that one I need.
And here's my Codes for adding an item to my ListView.
public void add(String destination, String Regulare, String Discounted, String Baggage) {
String [] rows = { destination, Regulare, Discounted, Baggage};
ListViewItem item = new ListViewItem(rows);
listView1.Items.Add(item);
}
private void btnAdd_Click(object sender, EventArgs e) {
add(textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text);
textBox1.Text = "";
textBox2.Text = "0";
textBox3.Text = "0";
textBox4.Text = "0";
MessageBox.Show("Record Added!","Saved",MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
tbDestination.Focus();
}
Like the other posters were saying, we don't know what your tech stack is or what problem you're trying to solve. Have you tried binding your list to a data source? Let's say you have a text box and a submit button for filtering. The user enters "California" into the text box and presses submit. You'll have a click handler in the code behind that invokes a DataBind() on your list. The method for your data bind will get the value of the textbox/hidden field and use it to return a conditional data structure that is then used to populate your list. You could even have a clear button that resets the filtering using the same method.
But it's been 16 days now, so you've probably already solved the problem. What did you end up doing?
Hı , Try this two way
First :
private void searchBox_TextChanged(object sender, EventArgs e)
{
// Call FindItemWithText with the contents of the textbox.
ListViewItem foundItem =
textListView.FindItemWithText(searchBox.Text, false, 0, true);
if (foundItem != null)
{
textListView.TopItem = foundItem;
}
}
Second :
void yourListView_MouseDown(object sender, MouseEventArgs e)
{
// Find the an item above where the user clicked.
ListViewItem foundItem =
iconListView.FindNearestItem(SearchDirectionHint.Up, e.X, e.Y);
if (foundItem != null)
previousItemBox.Text = foundItem.Text;
else
previousItemBox.Text = "No item found";
}
I just want to ask that Is it possible to start displaying options(for the text entered in textbox) in the listbox as soon as the user starts typing in the textbox?
Thanks.
Probably, you're looking for something like this:
Put ListBox on the form (myListBox)
Put TextBox (myTextBox in the implementation below)
Implement TextChanged event handler for the text box
Possible implementation
// When TextBox's Text changed
private void myTextBox_TextChanged(object sender, EventArgs e) {
string textToFind = (sender as Control).Text;
// Do all the changes in one go in order to prevent re-drawing (and blinking)
myListBox.BeginUpdate();
try {
myListBox.SelectedIndices.Clear();
// We don't want selecting anything on empty
if (string.IsNullOrEmpty(textToFind))
return;
for (int i = 0; i < myListBox.Items.Count; ++i) {
string actual = myListBox.Items[i].ToString();
// Now we should compare two strings; there're many ways to do this
// as an example let's select the item(s) which start(s) from the text entered,
// case insensitive
if (actual.StartsWith(textToFind, StringComparison.InvariantCultureIgnoreCase)) {
myListBox.SelectedIndices.Add(i);
// can we select more than one item == shall we proceed?
if (myListBox.SelectionMode == SelectionMode.One)
break;
}
}
}
finally {
myListBox.EndUpdate();
}
}
i am using custom auto source to the text box. But the problem is, when i am entering key , if the suggestion list is high then the textbox flickers before showing suggestion.
private void txtSearch_TextChanged(object sender, EventArgs e)
{
if (txtSearch.Text != "")
{
string templateSearchTxt = txtSearch.Text;
foreach (String template in templateName) // templateName contains list of string
{
if (template.ToUpper().StartsWith(templateSearchTxt.ToUpper()))
{
suggestion.Add(template);
}
}
}
}
I have declared following code on form load event
suggestion = new AutoCompleteStringCollection();
txtSearch.AutoCompleteCustomSource = suggestion;
txtSearch.AutoCompleteMode = AutoCompleteMode.Suggest;
txtSearch.AutoCompleteSource = AutoCompleteSource.CustomSource;
I will seriously encourage you to use a Combobox with its AutoCompleteMode set to Suggest and attach the autocomplete list to it (as its AutoCompleteSource). It'll performt way better than your textchanged event listener.
How do I create an Auto-complete ComboBox or TextBox that filters text based on a string?
For example: if I type an "a" in a TextBox, I only get to see all strings containing an "a".
If you mean show suggestions then it's a simple matter of changing a property when you have the TextBox selected in your IDE of choice:
The options shown in the picture allow you to change the rules for autocompleting text in the text box as well as the source for the suggestions. (Visual Studio 2010)
You can go to the following link to learn more about the TextBox control.
MSDN Text Box Control
Windows Forms's autocomplete implementation uses Shell's autocomplete object, which can only do a "BeginWith" match until Windows Vista.
If you can demand your users to upgrade to Windows Vista, you can use IAutoComplete2::SetOptions to specify ACO_NOPREFIXFILTERING. Otherwise I am afraid you need to write your own.
Here is how I auto-complete for a specific value in a comboDropDown box.
void comboBox_Leave(object sender, EventArgs e)
{
ComboBox cbo = (sender as ComboBox);
if (cbo.Text.Length > 0)
{
Int32 rowIndex = cbo.FindString(cbo.Text.Trim());
if (rowIndex != -1)
{
cbo.SelectedIndex = rowIndex;
}
else
{
cbo.SelectedIndex = -1;
}
}
else
{
cbo.SelectedIndex = -1;
}
}
This filters results based on user input. Optimizing for large lists, populating your own data and error handling left out for you to complete:
public partial class Form1 : Form
{
List<String> data;
ListView lst = new ListView();
TextBox txt = new TextBox();
public Form1()
{
InitializeComponent();
data = new List<string>("Lorem ipsum dolor sit amet consectetur adipiscing elit Suspendisse vel".Split());
}
private void Form1_Load(object sender, EventArgs e)
{
this.Controls.Add(txt);
lst.Top = 20;
txt.TextChanged += new EventHandler(txt_TextChanged);
lst.View = View.List;
this.Controls.Add(lst);
list_items("");
}
void txt_TextChanged(object sender, EventArgs e)
{
list_items(txt.Text);
}
void list_items(string filter)
{
lst.Items.Clear();
List<string> results = (from d in data where d.Contains(filter) select d).ToList();
foreach (string s in results)
{
lst.Items.Add(s);
}
}
}
To get the combobox to auto complete, set the AutoCompleteSource and AutoCompleteMode properties:
cbo.AutoCompleteSource = AutoCompleteSource.ListItems;
cbo.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
The ListItems source tells the combo to use it's items collection as the auto complete source.
I know this is an old topic but i tried so hard to find a solution for c# autocomplete filtering too and couldn't find any so i came up with my own simple and easy way so i'll just share it for those who may think it's useful and wanna use in their projects. It does not use the control's autocomplete features. What it does just simply get the text entered from the combobox, search it in the source then display only the matching ones from the source as the combobox' new source. I implemented it in the combobox' KeyUp event.
Let's say (actually this is what i do for almost all the cases when i want autocompleting) we have a globally assigned DataTable called dt_source to be the combobox' source and it has two columns: id(int) and name(string).
DataTable dt_source = new DataTable("table");
dt_source.Columns.Add("id", typeof(int));
dt_source.Columns.Add("name", typeof(string));
And this is what my KeyUp method looks like:
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
}
}
I think your best bet is to override the OnKeyDown(KeyEventArgs e) event, and use the value to filter the ComboBox.AutoCompleteCustomSource. Then as noted above, change the AutoCompleteSource to AutoCompleteSource.ListItems.