Why Bindinglist is not updating after database changed? - c#

I am working in Winforms Projects. In which whenever I add or edit record in database and close that from I want my list updated.
But in Search Form my list does not get updated. For that I have to Rebind Data Again from database. When I searched and got know about bindinglist then I used bindinglist instead of list, but it is still not working.
Here is my code
///
/// Represent FirstName Fields
///
public String FirstName { get; set; }
_MemberMaster.FirstName = Convert.ToString(txtFirstName.Text);
string result _IMemberMasterController.UpdateMemberMaster(_MemberMaster);
After update I closed my form, but in search form list not updating. As when list get updated I want datagridview get also updated.

I was about to reply in comments, but I want to give example code.
After the code to create a Form, for example
Form newForm = new Form();
newForm.Show()
or whatever method you use to make that form, add a formClosed event handler:
Form newForm = new Form();
newForm.FormClosed += new FormClosedEventHandler(f_FormClosed);
newForm.Show();
And then you can control what happens when the form is closed, so you can update your bindinglist easily.
void f_FormClosed(object sender, FormClosedEventArgs e)
{
myBindingList.ResetBindings(false);
}
Edit
And in your bindingList constructor: (assuming it contains strings)
private BindingList<string> _mybindinglist;
public BindingList<string> myBindingList
{
get { return _mybindinglist; }
set
{
_mybindinglist= value;
OnPropertyChanged("myBindingList"); // or RaisePropertyChanged or whatever you used
}
}

I Solved my problem with IUNotifyProertyChangedEvent....

Related

How to transport information from one form to another using dto, C# Windows Forms?

I'm having trouble transporting information from one form to another, is to make a single save, but the information is distributed in 2 forms and I have to do it using dto. I know that for this I have to send the data that I want by the form builder method, as you can see in the code below:
public FrmModalFornecedor(int providerId, int providerDoc)
{
InitializeComponent();
CbxListarFornecedor();
providerDoc = Convert.ToInt32(txtDoc.Text);
providerId = Convert.ToInt32(((Provider)cbxFornecedor.SelectedItem).ProviderId);
}
But now my questions are:
How to make these variables take their respective text box and combo box values?
How to make the next form have access to this data?
You can create additional properties in the second form and you can pass the values from first form to second form.
Hope this gives some ideas for you.
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.MyName = "Pass my name here";
frm.Show();
}
public partial class Form2 : Form
{
public string MyName { get; set }
public Form2()
{
InitializeComponent();
}
}

Save/Open Dynamically Created Controls In a Form

I am trying to develop a program in which it could create forms and add controls to it at runtime.
It also should be able to save, (Open and Edit) the forms created with the new controls added it at Runtime.The Application starts In the Main form.
CODE BEHIND MAIN Form
private void Btn_CREATE_FORM_Click(object sender, EventArgs e)
{
Form_Properties fp = new Form_Properties();
fp.Show();
}
private void BTn_ADD_BTN_Click(object sender, EventArgs e)
{
/// WHAT CODE SHOULD I ENTER TO ADD BUTON TO NEW FORM
}
Basically the main form is used to create/open/save new forms and add controls to it.
When the user clicks on Create New Form button the user will be presented with the following form (FORM_PROPERTIES) in which the user can customize the name, width and height of the new form.
CODE BEHIND FORM_PROPERTIES Form
public partial class Form_Properties : Form
{
public Form_Properties()
{
InitializeComponent();
}
String form_name;
int form_width;
int form_height;
private void Btn_OK_Click(object sender, EventArgs e)
{
form_name = TBox_NAME.Text;
form_width = Convert.ToInt32(TBox_WIDTH.Text);
form_height = Convert.ToInt32(TBox_HEIGHT.Text);
New_Form nf = new New_Form();
nf.Text = form_name;
nf.Width = form_width;
nf.Height = form_height;
nf.Show();
}
}
The following image shows what happens at runtime based on the code I have written so far.
ISSUES
Need help to Write Code
To add controls to new form created.
To Save/Open/Edit Functionalities.
I also need to know the method to access properties of added controls at runtime.
eg: If the user adds a text box to the NEW FORM and decides to type some text in it, I need a method to save that text.
Is there a way for me to name the added controls?
It seems you want to build some kind of WinForms' form designer. Your program would be similar to Glade (though Glade is much more powerful).
I'm afraid the question is too broad, though. There are many questions to answer, for example, how do you describe the created interface.
While Glade uses XML, you can choose another format, such as JSON. Let's say that you have a TextBox with the word "example" inside it.
{ type:"textbox" text:"example" }
It seems you want to add your components to the form as in a stack. Maybe you could add its position. For example, a form containing a label
("data"), a textbox ("example"), and a button ("ok"), would be:
{
{ pos:0, type:"label", text:"data" },
{ pos:1, type:"textbox", text:"example" },
{ pos:2, type:"button", text:"ok" },
}
But this is just a representation. You need to a) store this when the form is saved, and b) load it back when the form is loaded.
For that, you will need a class representing the components, such as:
public class Component {
public override string ToString()
{
return string.Format( "position:{0}, text:{1}", this.Position, this.Text );
}
public int Position { get; set; }
public string Text { get; set; }
}
public class TextBoxComponent: Component {
public override string ToString()
{
return base.ToString() + "type:\"textbox\"";
}
}
...and so on. This is a big task, I'm afraid, with no simple answer.

Form 2 textbox displays in form 1 listbox

I currently have two forms, one to display information when a user is selected from the listbox(the listbox lists names, when selected it will fill a few textboxes I have, one for city and another for address), the second form allows me to input the information for the user, which when I click submit will display them in my listbox on form1. Currently I am able to add the user from my second form to my first form into the listbox, but I am having issues filling their information in the textbox whenever I click on their names in my listbox.
As of now I have tried implementing different code snippets, but being a beginner I'm not sure how to do this.
My first form is as follows
public Form1()
{
InitializeComponent();
}
private void ButtonAddUser_Click(object sender, EventArgs e)
{
Form2 form = new Form2(textBoxFirstName.Text, listBoxUsers);
form.Owner = this;
form.ShowDialog();
form.Show();
}
private void listBoxUser_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBoxUser.SelectedIndex != -1)
{
User selected = (User)listBoxUser.SelectedItem;
textBoxStreet.Text = selected.Street;
textBoxCity.Text = selected.City;
}
}
My second form where I add the users information is as follows
public partial class Form2 : Form
{
private ListBox _listBoxUsers;
public Form(string value, ListBox listBoxUser)
{
InitializeComponent();
value=($"{textBoxFirstName.Text} {textBoxLastName.Text}");
_listBoxUsers = listBoxUsers;
}
private void ButtonSubmit_Click(object sender, EventArgs e)
{
_listBoxUsers.Items.Add($"{textBoxFirstName.Text}
{textBoxLastName.Text}");
this.Close();
}
}
And my Class where I am trying to store the textbox information
public class User : EventArgs
{
public string Street {get; set;}
public string City {get;set;}
public User(string street, string city)
{
Street = street;
City = city;
}
}
In Short: I'm trying to save information from my second form into my class, and when I select a user from my listbox it will display his street and city into textboxes (my listbox and textboxes are both on my first form.).
Thanks for any help
In the second form you should be creating User object and fill the details like street and city .
private void ButtonSubmit_Click(object sender, EventArgs e)
{
User user = new User(textBoxFirstName.Text, textBoxLastName.Text);
_listBoxUsers.Items.Add(user);
this.Close();
}
Since Listbox.Items expecting object type, you can add anything which is derived from System.Object. But in the form1 you have created list with User Objects and during selected index changed you are type casting as User Object. But in the form2 you have not actually inserted User object during the submit button click .
Because of this, i think you are facing this problem . Try with above code and check
I would suggest decoupling state management from the presentation. For example, try to create a separate class for User that is not derived from EventArgs. And manage its state inside a separate class - for start int will be in-memory storage. But as you flesh out your implementation you can latter move your data to Database with ease as it will not rely on UI and its elements for storage and management.

DataBinding DataGrid to ObservableCollection<T> is creating 2 different instances of the DataGrid and only the default is shown

The data binding works as it I intend, kind of... The real issue I'm running into now is what I believe to be 2 different instances of my User Control, but only the original, debug list I implemented is showing.
In short, I am building 2 lists that are technically bound to the data grid, the default debugging list I created in the default constructor and then the real list I created to bind to the data grid.
Every time I click on the user control with the data grid, the default constructor adds another line to my debugging list and displays it on the screen.
Every time I click the button that builds a list of selected options on a separate user control I can see my the options add on to the list of options I had been creating and technically set it to the data context of the data grid, the same way the default debug list does, except when I click back over to the data grid user control, the default constructor runs again, ads another line to my debug list, and displays the debug list that is being built.
Here's a copy of the class with a couple lines I added to help debug the problem.
public partial class QuotePreview : UserControl
{
private SelectionList _selectionList;
private SelectionList temp;
public QuotePreview()
{
InitializeComponent();
_selectionList = (SelectionList)this.DataContext;
}
private void QuotePreview_Loaded(object sender, RoutedEventArgs e)
{
//Adds item to Debugging list
_selectionList.SelectedOptions.Add(
new Selection
{
ModelNumber = "this",
Description = "really",
Price = "sucks"
});
}
public QuotePreview(SelectionList selectedOptions)
{
InitializeComponent();
_selectionList = (SelectionList)this.DataContext;
temp = selectedOptions;
//The list I am actually trying to display
_selectionList.AddRange(selectedOptions);
QuotePreview_Loaded();
}
private void QuotePreview_Loaded()
{
foreach (var options in temp.SelectedOptions)
{
_selectionList.SelectedOptions.Add(options);
}
QuotePreviewDataGrid.ItemsSource = _selectionList.SelectedOptions;
}
}
The implementation of the default constructor, is called every time the user control / tab, is clicked on. When that happens, _selectionList is set to the data context of the user control, followed by the Loaded Event which adds a line to my data grid.
In another user control where I select the options I want to add to my data grid user control, I click a button that creates a list of the options I want to be added and calls the custom constructor I wrote. Once the constructor finishes, it calls a custom Loaded Event method that I created for shits and giggles, that adds the selected options to my _selectionList.
Now once I click on the data grid user control again, it goes through the whole default process, and adds another default line.
If I go back a tab and say I want these options again and go back to the data grid, it again goes through the default process and adds another default line.
Whats most intriguing though is that I can see both of the selectionLists build since I dont clear the in between processes. I see a list build of the options i want to display and a list build of the default options build...
Oh, also, SelectionList does implement ObservableCollection
i don't follow exactly what you are asking but loaded event will fire whenever load is required and in your case you are switching between the views , TabControl will not render its content until it is required !
bool _isDefaultItemAdded = false
private void QuotePreview_Loaded(object sender, RoutedEventArgs e)
{
if(!_isDefaultItemAdded)
{
//Adds item to Debugging list
_selectionList.SelectedOptions.Add(
new Selection
{
ModelNumber = "this",
Description = "really",
Price = "sucks"
});
_isDefaultItemAdded = true;
}
}
I finally came up with a solution to the problem.
public static class QuotePreview
{
public static ObservableCollection<PurchasableItem> LineItems { get; private set; }
static QuotePreview()
{
LineItems = new ObservableCollection<PurchasableItem>();
}
public static void Add(List<PurchasableItems> selections)
{
foreach (var selection in selections)
{
LineItems.Add(selection);
}
}
public static void Clear()
{
LineItems.Clear();
}
}
public class QuoteTab : TabItem
{
public ObservableCollection<PurchasableItem> PreviewItems { get; private set; }
public QuoteTab()
{
Initialize()
PreviewItems = QuotePreview.LineItems;
DataGrid.ItemSource = PreviewItems
}
}

Update form from form closing event on another form

I am trying to update a datagridview on my 'switchboard' to solve a concurrency issue. The switchboard has many checkboxes to check off when certain processes are done. When I click a checkbox on a record that has been edited I get a concurrency error as the dgv is not up to date.
I tried doing this:
How to refresh datagridview when closing child form?
to no avail as it raises other errors throughout my project.
Any help on how to refresh my datagridview on my switchboard on the form closing of another form would be great.
Thanks
public partial class frmSwitch : Form
{
public frmSwitch()
{
//'add a label and a buttom to form
InitializeComponent();
}
public void PerformRefresh()
{
this.propertyInformationBindingSource.EndEdit();
this.propertyInformationTableAdapter.Fill(this.newCityCollectionDataSet.PropertyInformation);
this.propertyInformationDataGridView.Refresh() }
}
public partial class frmSummary : Form
{
frmSwitch _owner;
public frmSummary(frmSwitch owner)
//public frmSummary()
{
InitializeComponent();
_owner = owner;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmSummary_FormClosing);
}
private void frmSummary_FormClosing(object sender, FormClosingEventArgs e)
{
_owner.PerformRefresh();
}
That is what I attempted to do but it caused issues in other instances when I needed to open Form2. The issue specifically occurs in the original opening of form 2 which is as follows:
private void propertyInformationDataGridView_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
System.Data.DataRowView SelectedRowView;
newCityCollectionDataSet.PropertyInformationRow SelectedRow;
SelectedRowView = (System.Data.DataRowView)propertyInformationBindingSource.Current;
SelectedRow = (newCityCollectionDataSet.PropertyInformationRow)SelectedRowView.Row;
frmSummary SummaryForm = new frmSummary();
SummaryForm.LoadCaseNumberKey(SelectedRow.CaseNumberKey, true, null);
SummaryForm.Show();
}
It sounds like you are trying to create a new instance of your Switchboard form instead of modifying the existing instance of the form. When you open a form from the switchboard, I would suggest passing in instance reference to the switchboard form. Then, when you close the opened form, in your form_closing event you would refer to the passed in instance as the Switchboard form to update.
This method and others are specified in this article:
http://colinmackay.co.uk/blog/2005/04/22/passing-values-between-forms-in-net/

Categories

Resources