0
votes

For the start I am using Sql Server Local DB and Linq to Sql. I have two forms Form1 and Form2. There is a comboBox in Form1 that i want to update everytime it is shown. Form2 inserts new record and Form1 is for searching the record. After inserting a record when i go back to Form1. It doesnot update the list. I have tried Shown and Activated for Form1 and onClosing event for Form2 but to no luck. Also I have tried Enter event for comboBox. Though Database is updated but comboBox is not. That is how i update my comboBox

_Namelist.Clear();
_Namelist.Add("Select a Name");
_Namelist.AddRange((from p in context.Peoples
                          select p.Name).ToList());
comboBox1.DataSource = _Namelist;

I have created a separate class to make my main form that is FORM1 to be singleton. To show Form1 i have used this

FormProvider.Form_1.Show();

In this scenario how can i update my comboBox?

Update_1

If I try to search (in Form1) the new data that i have inserted (in Form2) then it finds the record perfectly, just not updating comboBox.

Update_2

I just made a new Class

public class Database
{
    static DataContext context;

    public static List<string> getNames()
    {
        context = new DataContext();
        List<string> _names = new List<string>();

        _names.Add("Select a Name");
        _names.AddRange((from p in context.People
                                   select p.Name).ToList());

        return _names;
    }

}

Calling this function in any Event call of Form1 is doing the job. Can anyone tell me why it didn't work in the scenario i have described above in my question?

3

3 Answers

1
votes

I would guess that it could be related to data caching in LINQ. Did you try refreshing the DataContext or flushing after creating the new record in Form2?

0
votes

Try this, make the method to update the combo box on Form1 public, then on the close event of Form2 call the method:

So on Form1:

public void PopulateNamelistComboBox()
{
    _Namelist.Clear();
    _Namelist.Add("Select a Name");
    _Namelist.AddRange((from p in context.Peoples
                      select p.Name).ToList());
    comboBox1.DataSource = _Namelist;
}

Then on Form2 in the constructor, add the event handler to call the close event:

public Form2()
{
    Closed += Form2_Closed;
}

Then add the method on Form2:

private void Form2_Closed(object sender, EventArgs e)
{
    FormProvider.Form_1.PopulateNamelistComboBox();
}
0
votes