Reputation: 191
I have read many other questions about this same thing but it seems the answers do not pertain to how I am performing my code. After adding or deleting a record or row of information to my database from the user interface it does not show in the combo boxes until I restart the application. Maybe someone can enlighten me as I am somewhat new to this. Below is my code when clicking the add button.
private void FBinterface_Load(object sender, EventArgs e)
{
txtSerial.Focus();
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string SerialQuery = "select SerialNumber from Inventory";
command.CommandText = SerialQuery;
//TO READ DATA
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
comboSerial.Items.Add(reader["SerialNumber"]);
}
connection.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
connection.Close();
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtSerial.Text))
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = @"insert into
Inventory(SerialNumber,PartNumber,ROnumber,Location)
values ('" +
txtSerial.Text + "','" +
txtPart.Text + "','" +
txtRO.Text + "','" +
txtLocation.Text + "')";
//TO READ DATA
command.ExecuteNonQuery();
MessageBox.Show("Inventory Added");
txtPart.Clear();
txtSerial.Clear();
txtRO.Clear();
txtLocation.Clear();
if (dataGridFB.DataSource != null)
{
dataGridFB.DataSource = null;
}
else
{
dataGridFB.Rows.Clear();
}
txtSerial.Focus();
connection.Close(); // CLOSE HERE OR
// YOU CANNOT ENTER RECORDS SIMULTANEOUSLY
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
connection.Close();
}
}
}
Upvotes: 1
Views: 1154
Reputation: 7918
As a simple fix, you may add the following code snippet before the line connection.Close()
in the btnAdd_Click
event handler:
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string SerialQuery = "select SerialNumber from Inventory";
command.CommandText = SerialQuery;
//TO READ DATA
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
comboSerial.Items.Add(reader["SerialNumber"]);
}
This code snippet will essentially re-bind the ComboBox
comboSerial
. The same goes to other ComboBoxes if their underlying data is affected by btnAdd_Click
procedure. Furthermore, it could be fruitful to create a dedicated procedure (something like ResfreshAllComboBoxes()
), place the code similar to the sample snippet above and call it after underlying data change.
Hope this may help.
Upvotes: 2
Reputation: 555
It's better to put codes in (FBinterface_Load) inside a new method, say FillComboSerial(), and then you have to call that method after inserting each new record right after closing the connection.
Upvotes: 1