Reload/Refresh data from DB periodically using entity framework 5 [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm using entity framework 5 on my winform application. I have a datagridView on my form which contains data from my database:
public partial class Form1 : Form
{
etudiantEntities cont = new etudiantEntities();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cont.etudiant1.Load();
etudiant1DataGridView.DataSource = cont.etudiant1.Local;
}
Right now, every thing is perfect.
Now, i want to reload data when there is an update happened in other forms. I want to reload it periodically.
Is there a way to do that with entity framework?
Thank you!

You have like five problems at once. Writing a proper answer would require a book (which I would suggest you to go read anyway), so this answer is a summary you can use to learn more.
First, you need to elaborate on "when there is an update happen[ing] in other forms". You need to detect this change. How to do that, depends on how that form works. Hopefully it does using data binding and INotifyPropertyChanged, see Raise an event whenever a property's value changed?.
Then on these "other forms", you subscribe to their model's PropertyChanged event and propagate that as an event on each form. Be sure to unsubscribe when appropriate as well. In the PropertyChanged event handler of your form, you raise an event that's specific to that form, like MyModelChanged.
Now you have a form that can notify interested parties of events, by subscribing to that event.
Something like this:
var yourEditForm = new YourEditForm();
yourEditForm.MyModelChanged += this.YourEditForm_MyModelChanged;
yourEditForm.Show();
Now where you place this code is pretty crucial. When working with multiple forms you want to communicate with each other, you need some kind of "controller" (or give it a name) that knows about all forms and their events that are relevant to your application, and ties it all together.
So in your controller you now have the above code and this event handler:
private void YourEditForm_MyModelChanged(object sender, EventArgs e)
{
}
Now in that event handler, you can let your aptly named Form1 reload its data. You can do so by exposing a public method that does just that:
public void RefreshGrid()
{
cont.etudiant1.Load();
etudiant1DataGridView.DataSource = cont.etudiant1.Local;
}
There's your "refresh". You can call form1.RefreshGrid() in the event handler shown above.
Note that all of this is pretty much hacked together. Go read a tutorial or two about data binding in WinForms to let this properly be handled, because doing it manually is going to be a pain to maintain.
You can start by reading Data Binding and Windows Forms and Change Notification in Windows Forms Data Binding on MSDN.

Related

Create a void method for each button

Hi im hoping someone can assist im still new to programming and this is a noob question but i have created a Visual studio - C# (Windows Form Application) and now the question reads to Create a void method for each of my buttons i created in the form and telling me even what to name the method.
but on my research The void keyword is used in method signatures to declare a method that does not return a value.
LinkToAddresses () will be my void method for address the (button), so my question is do i just put in this void method and its going to do nothing?
im just going to link the full question maybe im just really not understanding this>?
''
The below form will represent the main form from which the user will navigate to the other forms. Meaning each button should be linked to the appropriate form. E.g. If button Manage Addresses is clicked the form managed addresses should be displayed. The Exit button should successfully terminate the program.
Create a void method for each button and name them as follow: LinkToAddresses (), LinkToCustomers (), LinkToDrivers (), LinkToStatus (), and LinkToFreight (). The methods should be called under the appropriate button. For the exit button create a void method named AppExit () this should terminate the program.
''
I would appreciate any help or guidance, thank you in advance.
Visual studio usually handles the button actions easily. Just place the buttons on your form, then rename the buttons to LinkToAddresses, LinkToCustomers, LinkToDrivers, LinkToStatus, LinkToFreight and AppExit. Then simply just double click on the each button and visual studio will create a void method for their click event.
using System;
using System.Windows.Forms;
namespace YourApp
{
public partial class FormMain : Form
{
private FormManagedAddresses formManagedAddresses = null;
public FormMain()
{
InitializeComponent();
}
private void LinkToAddresses_Click(object sender, EventArgs e)
{
if (formManagedAddresses != null)
{
formManagedAddresses.Close();
}
formManagedAddresses = new FormNews();
formManagedAddresses.Show();
}
private void AppExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
The closest thing to a buttons function, is the Click Event Handler. While specific names vary based on Display technology (WinForms, WPF/UWP, ASP.Net), that is the general pattern for Graphical User Interfaces. It is called event driven programming. Even things that have a different programm flow like Games and Web Applications usually try to imitate it.
The signature of a event is given during its definition and must be strictly followed. Usually void NameOfTheEvent(object sender, SampleEventArgs e).
A return type of void is extremely common with events. If there is to be any output, that usually is handeled via a property in the Event Args or by directly doing stuff with the other GUI Elements.
If you want a button to do nothing, you just never give it a event handler. Every single button you ever used, was given a implicit or explicit event handler to do exactly what it did. If you want it to conditionally do nothing, either disable the Button so it can not be clicked, or put a proper if-statement into the event Handler.
A advanced topic would be the command pattern, where there is a bunch of commands in code behind. And each button, menu item and key combination is meerely a way to trigger said command - a representation for hte user to call the command.
You can share a single event across any number of Elements. AS you can see above, the pattern for events includes object sender as argument. This means you can check if it is a specific Button instance that called the event. Or even "unpack" the specific button, do look at stuff like Display String, Tag to get data from it. However, as a general rule retrieving data from the GUI is a bit frowned - ideally the GUI should only represent the data in the backend.

How to access design Windows Forms C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Pretty much new to Windows Forms, I know the C# language, just not in the same context. I have searched around for a while and it seems to me that every solution is doing something similar to this:
Label1.Text = "I'm a label".
But I don't understand where Label1 is coming from.
All I have is a new Windows Form Application, which comes with one form preloaded and a Program class. So as this class came with some code, I thought this would be a logical way of accessing the label's properties:
static class Program
{
static void Main(String[] args)
{
FormUpdate frmUpdate = new FormUpdate();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(frmUpdate);
// Why isn't this a suitable way of getting the label?
frmUpdate.label1.Text = "I cause an error!";
}
}
But I don't understand where Label1 is coming from.
Someone used the Visual Studio Designer for Windows Forms and dragged and dropped a Label component onto their form. As Visual Studio has no way of naming them, but needs a name, it simply counts up. The first dropped label is called "Label1".
The access specifier for those controls added is private by default and I'd suggest to leave it that way. If you want to interact with your form, either do it from inside your form or write a public method that you call that will then set all the private properties like the text of a certain label.
Generally speaking, Application.Run(frmUpdate); is running the program, based on the starting form you gave. Anything after that will have little effect. So you ran your form and after you closed it, you set the label. That's not going to have any visible effect. You need to do that before you run the form or while you are running it.

How to create an object which runat server asp [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I wish to define a timer, however, the timer which define in my asp.net behind code doesn't work.
When I create the timer in the html, which enable runat server is running perfectly.
How I can define a timer on the behind code, with the runat = "server" attribute?
private Timer loopMessage = new Timer();
protected void Page_Load(object sender, EventArgs e)
{
loopMessage.Tick += new EventHandler<EventArgs>(loopMessage_Tick);
loopMessage.Interval = 3000;
loopMessage.Enabled = true;
}
This code doesn't work, the event is not able to execute
You never added the Timer to the page.
It's created at the class level, but the class is disposed immediately upon handling the HTTP request and no server-side state is maintained for it. So every request is essentially creating a Timer and then disposing it.
If Timer is indeed a page control, it would need to be added to the page. I'm not entirely familiar with this control, but if it needs to emit JavaScript to the client in order to invoke things at given intervals then the control would need to be on the page to make that happen.
Something like this, perhaps:
this.Controls.Add(loopMessage);
Like David said, this code actually creates a new timer on every postback. And if your timer is not in an update panel, then every tick triggers another postback. So if I understand your problem correctly, first you must add an update panel on your page, then maybe you can add that update panel's controls to this timer.
Or you can leave all that ASP.NET problems here and turn to javascript timer and use jquery ajax method to solve your problem. Be sure that this will be way more effective for this problem and your future projects.

How can we access dynamically created controls in C# windows application? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am designing C# windows application using 3-Tier architecture, Basically i am making management system for super market in which i have created a form for generating BILL. I have used FlowLayout panel for generating 4 ComboBoxes, 3 TextBoxes and 2 Numeric UpDown respectively to hold Bill values accordingly. I have supplied add button with which we can create these controls dynamically on each button click, so, for example, when user clicks on the add button to add new item, new row will be generated with 4 CBs, 3 TBs and 2 NUpDowns. Having mentioned the scenario, I have following queries:
How can i access each and every of the control in each row in turn? So, for example, I want to access 3rd ComboBox of 5th row, How can I access that in particular.
I am using 3-tier application architecture to design the application. I have placed their functions in BusinessLogicLayer and have called them in UI in button event. Am i alright with this approach?
I want each ComboBox, in each row, to be connected with the first one. for example first one indicates main category when user selects anything from that, second combo box(sub category) should show items connected with the first one and so on. How can i do that?
Thanks
I don't know the very architecture of your application, but let me try and help you. Assumed you have some sort of Customer, Product and Order objects for your business logic the workflow could be the following
void ButtonFindCustomer_Click(object sender, EventArgs e)
{
m_order.Customer = Customer.Find(TextBoxFirst.Text, TextBoxLast.Text, TextBoxCustomerID.Text);
}
void ButtonAddProduct_Click(object sender, Event args)
{
m_order.AddArticle(Product.Find(TextBoxArticleNumber.Text), NumericUpDownArticleAmount.Value);
}
void ButtonSubmit_Click(object sender, EventArgs e)
{
m_order.Place();
}
I used the prefix for the member variable here just for clarity, for the lack on context. In your real code you should avoid it. Furthermore I have omitted the check if the user exists in ButtonFindCustomer_Click, this case should be handled, too. In ButtonAddProduct_Click the case a product is added is handled. Again the existence of the product is assumed, thus you'll have to introduce some error handling here, for example by using something like
if(Product.Exists(productNumber))
{
// add to order
}
else
{
// emit error message
}
The actual transaction is performed in the ButtonSubmit_Click handler. The order is validated and then sent to the data access layer (for example written to a SQL-Database). Once again the error handling is missing, please keep that in mind.
To get to your actual questions:
1) You'll somehow have to keep track the controls you created. If you are always creating them in the same groups, you should consider a user control, which avoids keeping track of which controls belong together. The control could - for example - contain a drop down box for categories, a drop down box for products and a numeric up down for the amount.
class ProductSelector : UserControl
{
... //add controls to user control
public event EventHandler CategoryChanged;
public event EventHandler ProductChanged;
...
public void PopulateCategories(list<string> names, list<string> ids)
{
...
}
public void PopulateProducts(list<string> names, list<string ids)
{
...
}
}
Now any time anything about the product is changed, you'll receive an event and can directly access your user control and all necessary data (if you wrote the functions in ProductSelector). If you want to access the controls in turn, you can either get all controls of type ProductSelector from MainForm.Controls or create a list of all ProductControls you added.
2) Yes, I think you'll be alright with this approach. Somewhere you'll have to access the functions of your BLL and UI event handlers are a good starting point for.
3) Please see me answer to 1).
I hope my explanation met your requirements and answered you questions. Feel free to ask, if I may help you any further.

Raise custom events in C# WinForms

I have some Events I created on my own and was wondering on how to raise them when I want.
Probably my application design is also messed up, might take a look at that if you like.
This is the Structure
ProgramContext
- Form MainWindow
+ Control TextBox
+ Control Button
+ ...
In this case, the MainWindow.TextBox holds some information that is updated quite often at runtime. So, I somehow need it to refresh itself when I want to (so it can reload its data from the database, where the it's stored)
I tried hooking an EventHandler to its Validating-Event, but that didn't seem to do the trick.
So, basically I have a method that reloads the data in ProgramContext
DataTable table = _adapter.GetData();
foreach (DataRow row in table.Rows)
{
MainWindow.TextBox.Text += table.Text.ToString();
}
That needs to be done whenever another method (that writes new data into table) is executed.
Any ideas?
Edit : It seems your question is more about hooking into a specific event, but FWIW below is how to fire custom events in general.
Handling the TextBox Changed Event
From what I understand, you want an external party to monitor events raised from a textbox on a Form and then to reload data on another form?
A quick and dirty would be to make the Form TextBox public and then others could subscribe to this event
MainForm.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
OR, in more recent versions of C#:
MainForm.textBox1.TextChanged += this.textBox1_TextChanged;
Adding Your own Custom Event
Another, cleaner way would be to raise a custom event, - e.g. MyDataChangedEvent below. This will allow you to abstract away the fact that the changes are coming from a textbox at all.
// Assuming you need a custom signature for your event. If not, use an existing standard event delegate
public delegate void myDataChangedDelegate(object sender, YourCustomArgsHere args);
// Expose the event off your component
public event myDataChangedDelegate MyDataChangedEvent;
// And to raise it
var eventSubscribers = MyDataChangedEvent;
if (eventSubscribers != null)
{
eventSubscribers(this, myCustomArgsHere);
}
You might also look at the Ent Lib Composite Application Block and Smart Client Software Factory - this has a very flexible event broking / pub sub mechanism for synchronising across UI "SmartParts" (controls, forms dialogs etc) in a loose-coupled fashion. (CAB is now very dated).

Categories

Resources