Populate Combobox based on value of textbox in wpf c# - c#

I have 1 textbox and 1 Combobox. Now what i want to do is that when user type in Textbox and then when he clicks on ComboxBox the combobox should automatically get filled from database. Below is my code.
public void BindComboBox3(ComboBox comboBox3)
{
SqlDataAdapter da = new SqlDataAdapter("Select batch_id FROM batch where product_id_fk='"+Convert.ToInt32(textBox2.Text)+"'", con);
DataSet ds = new DataSet();
da.Fill(ds, "batch");
comboBox3.ItemsSource = ds.Tables[0].DefaultView;
comboBox3.SelectedValuePath = ds.Tables[0].Columns["batch_id"].ToString();
}
private void comboBox3_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
BindComboBox3(comboBox3);
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("Enter Product ID " + ex.Message);
}
}

The selection changed event of the combo box should fire after the user click and select a different option. As if your combo box has nothing inside, the user have no way to change oneself the preference. That means the user have to do an extra clicking to fire it, or it just never fires.
You might consider other firing mechanism, such as MouseUp or MouseDown, MouseHover of the combox. You could set a breakpoint at the start of the event, so that you could know whether the event is fired from time to time, while you could separately ensure your code that update from the database does work.
Alternatively, you can trigger the combo box to change through the firing text changed event of the textbox.
Hope it helps.

Related

Windows Forms Combo Box Text doesn't update when I manually change the text in the SelectedValueChanged Event

I have the following code
private void cbAddTicketItem_SelectedValueChanged(object sender, EventArgs e)
{
string[] arr = cbAddTicketItem.Text.Split(' ');
cbAddTicketItem.Text = arr[0];
}
cbAddTicketItem is the combo box where the user is selecting from a list of items. The text of each item includes a description. I want to get rid of the description and just keep the value. Debugging shows that cbAddTicketItem.Text has the correct value but the text doesn't change on the form.
I think the issue is that either winforms is not firing the textChanged event, or it is overwriting it after my coded event runs.
You're making life rather hard work. It's easier if you do something like this:
var dt - new DataTable();
dt.Columns.Add("Disp");
dt.Columns.Add("Val");
dt.Rows.Add("Mark","1");
dt.Rows.Add("Luke","2");
dt.Rows.Add("John","3");
someCombo.DisplayMember = "Disp";
someCombo.ValueMember = "Val";
someCombo.DataSource = dt;
And then in some button click, let's say:
MessageBox.Show((string)someCombo.SelectedValue); //shows 2 if Luke is selected, etc

c# combobox automaticaly populated by inputed mysql data

I have two user controls. One is to input data and another one has a combobox that displays data from my MySQL table.
The use types in data in the first user control and presses a button. This adds the data to a MySQL table. I want to add the data immediately / automatically into the combobox (the other user control).
I would prefer not doing it using an event. If it is not possible and I have to use an event, what event should I use? Can it be an event not associated to the button?
Here is the method that reads data from MySQL and adds it to the combobox :
private void LoadFromDatabase()
{
string query = "select name from country";
MySqlConnection conn = new MySqlConnection(connection);
MySqlCommand command = new MySqlCommand(query,conn);
MySqlDataReader Read;
conn.Open();
Read = command.ExecuteReader();
while(Read.Read())
{
metroComboBox1.Items.Add(Read.GetString("name"));
}
conn.Close();
}
The current result is that I must reload the windows form to load the new data into thecombobox. Without the reload, the combobox only displays the old data. I have put that method under InitializeComponent(); of the combobox user control.
You can use the event click on the comboBox itself, so whenever you click it to open the dropdown it will update the combobox. Make sure to clear the items at the top of the click event to prevent duplicates.
If you truly insist on having no events, you can use a background worker, however for what you're doing it seems like overkill to spawn a thread just for that.
This is an idea of what the final result should look like.
private void comboBox1_Click(object sender, EventArgs e)
{
if (comboBox1.Items.Count > 0)
comboBox1.Items.Clear();
LoadFromDatabase();
comboBox1.SelectedItem = 0;
comboBox1.Text = "Select Item";
}

ComboBox SelectionChanged Event shows previous Items [duplicate]

This question already has an answer here:
ComboBox SelectionChanged event fires late
(1 answer)
Closed 5 years ago.
I have 2 ComboBoxes. And the Second ComboBox will Enabled when i Choose/Change the Item in the first ComboBox. But the Second ComboBox always shows me the previous Items.
For example:
I change Item in ComboBox 1. And ComboBox2 don't show me any items.
I change Item in ComboBox 1 again. Now ComboBox2 shows me the items which should shown by first change.
Here is my Code:
private void categoryComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
subCategoryComboBox.Items.Clear();
subCategoryComboBox.IsEnabled = true;
string SelectedCategoryID = ConvertBackCategory(categoryComboBox.Text);
connection = new MySqlConnection(conf.connection_string);
if (this.OpenConnection() == true)
{
try
{
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = connection;
cmd.CommandText = "SELECT name FROM auftrags_typ_childcategory WHERE category = #CategoryID";
cmd.Parameters.AddWithValue("#CategoryID", SelectedCategoryID);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
subCategoryComboBox.Items.Add(reader["name"].ToString());
}
}
}
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
How I can fix this? / Why it shows me not the current items?
The Text property of the WPF ComboBox is not updated until after the SelectionChanged event is raised. Don't ask me why, but it isn't. They seem to have intended the Text property only to be used for combo boxes with editable text.
Every other relevant property of the ComboBox is updated before SelectionChanged is raised.
SelectedItem, SelectedValue, and SelectedIndex will all be correct and current in your SelectionChanged handler. I answered this question yesterday; you should be able to adapt that answer to your needs without too much trouble, but let me know if you hit a snag.

Updating selected row to database with button click

I need to update selected row in datagrid when i click on button Ponuda.
The problem is, when i click on button, nothing happens, but when i restart application, whole list is updated. So i need a way to update only the row i have selected and to update it right away and not after application restart.
This is my code for button click :
private void button3_Click(object sender, RoutedEventArgs e)
{
// count = 120;
// tmr.Start();
using (SqlConnection conn = new SqlConnection(#"data source=ZC-PC\SQLEXPRESS;database=Aukcija;integrated security=true;"))
{
DataTable cena1 = new DataTable();
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter(" UPDATE Predmet SET trenutnaCena = trenutnaCena + 1", conn);
SqlCommand cmd = new SqlCommand("UPDATE Predmet SET trenutnaCena = trenutnaCena + 1", conn);
cmd.ExecuteNonQuery();
DA.Update(cena1);
conn.Close();
}
}
If you are using bindings, it SHOULD be updating. The reason it might not be is if whatever object your binding to the DataGrid (which should be an ObservableCollection or class based on one) does not implement INotifyPropertyChanged, the collection will never know a property change occurred.
If you haven't already, implement INotifyPropertyChanged and raise OnPropertyChanged event for each property. Then, when a value changes, it'll reflect both in the DataGrid and the actual collection being bound.
You'll want to make sure you have an event that updates the database with the new collection values whenever such and such happens (which I noticed button3_Click takes care of).
If this doesn't work, let me know, because it should.

WinForms ComboBox DropDown and Autocomplete window both appear

I've got a ComboBox on a winforms app with this code:
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
DataTable t = new DataTable();
t.Columns.Add("ID", typeof(int));
t.Columns.Add("Display", typeof(string));
for (int i = 1; i < 2000; i++)
{
t.Rows.Add(i, i.ToString("N0"));
}
comboBox1.DataSource = t;
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "Display";
I then follow these steps when the window opens:
Click the ComboBox drop down button -- this displays the list of items and selects the text in the ComboBox
Type '5', '1' ... i.e. I'm looking to use autocomplete to search for 515, 516, etc.
You'll see that the autocomplete window now appears ON TOP of the drop down list. However if I mouse over, it's the obscured drop down window behind the autocomplete window that's receiving the mouse events, including the click. So I think I'm clicking on an autocomplete item but actually clicking on something totally random that I can't see.
Is this a bug in the ComboBox? I'm using Windows 7 if that matters. Am I configuring the ComboBoxwrong somehow?
Note also that using the KEYBOARD uses the autocomplete drop down. So up/down arrow keys are using the front window, but the mouse is using the back window.
Add a single line of code to your ComboBox KeyDown event and the problem is solved!
private void comboBox_NameAndID_KeyDown(object sender, KeyEventArgs e)
{
comboBox_NameAndID.DroppedDown = false;
}
Source
No problem getting a repro for this simply by setting the properties from the PropertyGrid. Behaves this way both in Win7 and Windows XP.
This is broken behavior documented in this feedback article. As indicated, Microsoft is not considering a fix. One possible workaround is to disable autocomplete in a DropDown event handler and re-enable it in a DropDownClosed event handler.
I'm a Brasilian student of encoding and I lose many hours seeking to fix it im my project. And here, I saw it in a few seconds!!!
My code seems like this:
private void populateCombos()
{
persist.ShowLst(dspMember, vlMember,varTable,lstBox,varWhere);
persist.ShowLst(dspMember, vlMember,varTable,ddlist1,varWhere);
persist.ShowLst(dspMember, vlMember,varTable, ddlist2,varWhere);
ddList1.Text = null;
ddList2.Text = null;
lstBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
lstBox.AutoCompleteSource = AutoCompleteSource.ListItems;
lstBox.Text = null;
}
Add to the/a keypress event.
Dim box As ComboBox = sender
box.DroppedDown = False
Select the ComboBox from the design view and set "Append" to the AutoCompleteMode property, this will suggest the item without apearing a window.
That's weired. Your code looks fine to me and I used this the AutoComplete feature a several times and it didn't show both the DropDown and the AutoComplete list.
My suggestion would be
Set the DataSource after the Display/Value Members. I can't remember why but the other caused some problems.
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "Display";
comboBox1.DataSource = t;
Set the AutoCompleteSource at the end of your code (after adding the DataSouce)
Maybe that helps.
to only have one open at a time you can use comboBox1.Droppeddown = true open up the regular, false the AutoComplete will only appear
You simply add item in collection.
Now go properties option of combo box choose
AutoCompleteSource=ListItems
AutocompleteMode=suggest
note: autocomplete source have many option as per your requirement :)
WinForms ComboBox DropDown...the answer is this...
write below code in comboBox1 Enter event..
private void comboBox1_Enter(object sender, EventArgs e)
{
comboBox1.DroppedDown = true;
}
Now for comboBox1 AutoComplete...
write this AutoComplete() in page load event..so it work...
public void AutoComplete()
{
try
{
MySqlConnection conn = new
MySqlConnection("server=localhost;database=databasename;user
id=root;password=;charset=utf8;");
MySqlCommand cmd = new MySqlCommand("select distinct
(columnName) from tablename", conn);
DataSet ds = new DataSet();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(ds, "tablename");
AutoCompleteStringCollection col = new
AutoCompleteStringCollection();
int i = 0;
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
col.Add(ds.Tables[0].Rows[i]["columnName"].ToString());
}
comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
comboBox1.AutoCompleteCustomSource = col;
comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
Select the ComboBox from the design view and set "None" to the AutoCompleteMode property.

Categories

Resources