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";
}
Related
I’m building a windows dataGridView (DGV) form app using a table in a sqlserver as data source. The automatically created BindingNavigator works fine when the form is first opened.
The project has a requirement to be able to do a multi-column-sort. The user can click on the column headers and build a list of cascading “Order By” terms that is appended to a select command.
Once all the desired columns are selected the user clicks a button that performs the sql command. The desired result is then displayed in the DGV.
However, after performing the select the DGV no longer responds to BindingNavigator. It seems the navigator is no longer bound to the DGV.
This is the button click event code:
private void btnMultiSort_Click(object sender, EventArgs e)
{
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
if (selectedColumnOrder.Count > 0)
{
string sortOrderCSV = string.Join(",", selectedColumnOrder); // Convert List-type to CSV string to use in SQL statement
sqlConnection.Open();
string sql = $"SELECT * FROM PendingProjects ORDER BY " + sortOrderCSV + sortOrder;
SqlDataAdapter sqlDataAdapt = new SqlDataAdapter(sql, sqlConnection);
pendingProjectsDataGridView.DataSource = this.pendingProjectsBindingSource;
pendingProjectsDataGridView.Update();
txtBxColSortOrder.Text = displaySortOrderString;
sqlDataAdapt.Fill(dataTbl_1); // Fill data from DB-Table into inmemory DataTable-Oject (dataTbl_1) using the SqlDataAdapter (sqlDataAdapt_1)
pendingProjectsDataGridView.DataSource = dataTbl_1;
}
}
}
I'm using the table adapter in C# where I created a DataGridView. When I double click a row, I am displaying all the cells in the row in textboxes in a different Form. After I edit the textboxes and click my save button, I would like to take the values from the textboxes and replace them in the database. I can see the changes on the DataGrid, however I am not able to save them in the database.
private void InventoryData_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
//make new form and display them there
ViewInventoryItem ViewItem = new ViewInventoryItem();
ViewItem.textBox1.Text = this.InventoryData.CurrentRow.Cells[1].Value.ToString();
ViewItem.textBox2.Text = this.InventoryData.CurrentRow.Cells[2].Value.ToString();
ViewItem.textBox3.Text = this.InventoryData.CurrentRow.Cells[3].Value.ToString();
ViewItem.ShowDialog();
if (ViewItem.DialogResult == DialogResult.OK)
{
//save button was pressed
this.InventoryData.CurrentRow.Cells[0].Value = ViewItem.textBox1.Text;
this.InventoryData.CurrentRow.Cells[1].Value = ViewItem.textBox2.Text;
this.InventoryData.CurrentRow.Cells[2].Value = ViewItem.textBox3.Text;
this.Validate();
this.InventoryData.EndEdit();
this.booksTableAdapter.Update(this.InventoryDataSet.Books);
}
}
Found the problem. In the Dataset the Table had only Fill and Get Data. Even after selecting the Wizard to add the other statements it was failing. After adding the UpdateQuery manually, the code works without issues. Thank you Crowcoder for pointing me in the right direction.
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.
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.
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(ConnectionString)
{
connection.Open();
SqlCommand cmd = new SqlCommand("update dictionary set word=#word", connection);
cmd.Parameters.AddWithValue("#word", wordTextBox.Text);
cmd.ExecuteNonQuery();
this.Close();
}
}
I created a way to take a selected value in a listbox and add the item to a text box on a seperate form. There I am attempting to give the user a way to change that word and have it reflected in the dataset I created. Currently when I change that word it replaces every entry in my dataset with the new word as opposed to just the specific entry. I am trying to figure how to specify just to change that one item.
That is because you are missing a WHERE clause in your query. You need to use a WHERE clause in your query to only update some selected records that you like :
eg : update dictionary set word=#word WHERE ID=#ID.
This is just an example. You have to put the WHERE clause as per your requirement.
Hope this helps.