Passing Variable from one WPF Window to Another (C#) - c#

I really feel bad for having to ask this. The answer should probably be obvious; however, I have searched here and on Google to no avail.
I am quite new to WPF. With Windows Forms, I recall it was quite easy to pass data between Windows, but I cannot figure it out with my WPF application.
I am simply building an application for myself that will allow me to access and insert data in a MySQL database. When the button I have added to view all the records in a table is clicked, I want a new window to open. This window will simply display all the data; the table will be selected in MainWindow.
The problem I have is this: I need someway for the secondary window (View) to know which table was selected. I will probably use a ListBox control for table selection, but at the end of the day it really does not matter. Eventually, the value will be stored as a string in a variable. I need the View window to be able to access this string so it knows which table to query. In example:
// Main Window
private void viewButton_Click(object sender, RoutedEventArgs e)
{
var table = "DS";
View viewWindow = new View();
viewWindow.Show();
}
// View Window
private void windowLoad(object sender, RoutedEventArgs e)
{
DatabaseConnection myConnection = new DatabaseConnection();
List<string>[] result = myConnection.Select(table);
text.Text = MainWindow.test + (result[0][0] + " " + result[1][0] + " " + result[2][0] + " " + result[3][0]);
}
All I need to do is to pass the value of table (which will vary in the final application based on user input), to View. For example, I need it so that in the above code, the following would be executed:
List<string>[] result = myConnection.Select("DS");
I feel like this should be obvious and easy, but I am not sure how to accomplish this. I would sincerely appreciate any help.

You can pass a variable through constructor, like this
public View(string table)
{
this.table = table;
}
And when you initialize your window:
var table = "DS";
View viewWindow = new View(table);
viewWindow.Show();

Related

Fragment: Passing items from ListView to Firebase Realtime Database (Xamarin Android C#)

My listview is from a fragment and I want to pass all the inputted data at once in the listview to firebase. I have not seen any source about "ListView to Firebase" it's usually "From Firebase to ListView" so I have decided to ask this question.
This is what I did temporarily until I find the solution on passing values from ListView to Firebase Realtime Database. I don't know how to put values from ListView to Firebase so what I did is to put items from EditText to Firebase in a click of a button which is not what I needed.
private void AddpackageinfoButton_Click(object sender, EventArgs e)
{
if (infonamecrud.add(packageinfonameText.Text) && infoqtycrud.add(packageinfoqtyText.Text))
{
string packageinfoname = packageinfonameText.Text;
string packageinfoqty = packageinfoqtyText.Text;
Java.Util.HashMap packageinfo = new Java.Util.HashMap();
packageinfo.Put("infoName", packageinfoname);
packageinfo.Put("infoQty", packageinfoqty);
{
DatabaseReference newPackageInfoRef = AppDataHelper.GetDatabase().GetReference("packageinfo").Push();
newPackageInfoRef.SetValue(packageinfo);
}
infonameadapter = new ArrayAdapter(this.Activity, Android.Resource.Layout.SimpleListItem1, infoName);
packageinfonameListView.Adapter = infonameadapter;
infoqtyadapter = new ArrayAdapter(this.Activity, Android.Resource.Layout.SimpleListItem1, infoQty);
packageinfoqtyListView.Adapter = infoqtyadapter;
}
}
else
{
Toast.MakeText(this.Activity, "Please input all fields!", ToastLength.Long).Show();
}
}
FOR MORE DETAILS:
This is my layout and the ADD INCLUSIONS Button doesn't have a function. It is for the items in listview to be passed in database all at oncec.
This is how it would look like in the firebase. I need them all in one key.
What I need is passing all items in listview all at once. I just temporarily applied the hashmap every add button just to fill up the database and but the problem is the retrieval because they would have different key values.
Is there any syntax for this? Thank you so much for future answers. I appreciate it a lot! :)

What is best practice with regards to communicating between a user control and parent page?

I've been tasked with refactoring a mess of a page, and I would like to refactor it in the best way possible. The layout page is 600+ lines, and the code file is nearly 1400. I would like to separate different modules of the page into user controls, but those modules are receiving information, unsurprisingly, from the page they're on. For a short sample:
private void btnGetItem_Click(object sender, System.EventArgs e)
{
product = Products.getAllItemInformation(txtItemNbr.Text);
txtDescription.Text = product.getDesc();
setListBoxSelected(listMarketingSegment, product.getMarketingSegment());
}
private void setListBoxSelected(ListBox box, string pipeDelimitedStr)
{
pipeDelimitedStr = pipeDelimitedStr.Replace((char)253, '|');
pipeDelimitedStr = pipeDelimitedStr.Trim('|');
pipeDelimitedStr = "|" + pipeDelimitedStr + "|";
foreach (ListItem item in box.Items)
{
if (pipeDelimitedStr.IndexOf("|" + item.Value + "|") >= 0 && item.Value.Trim().Length > 0)
{
item.Selected = true;
}
}
}
How can I allow this functionality? A user control needs to be able to access that same product from the parent page, but I'm not sure what the best practice is for that to happen.
I read http://www.codeproject.com/Articles/8797/Mastering-Page-UserControl-Communication, but I'm not sure how to relate it to my situation. Do I create an interface? Create event driven communication? If so, how do I pass the product information to that user control?
You can do it MVVM way. Create a ViewModel, inherit from INotifyPropertyChanged, define properties for you data. Set datacontext of your parent page and usercontrol as your ViewModel and keep on updating properties. Now on usercontrol and on parent page you can access data using these properties. Here is one example. you will find many more links/example over the net to implement things MVVM way.

Why are my list controls being cleared after being populated in WizardStep0 in an ASP.NET Wizard control?

I'm using a Wizard control in an ASP.NET application. In several of the WizardSteps, I'm populating a DropDownList and a CheckBoxList in the Activate event of the step. This works correctly in all steps except WizardStep0. What's happening is that the code is running to populate the lists, but once rendering is complete on WizardStep0, the list controls are empty, as if they've been cleared.
Here's the WizardStep0_Activate method:
protected void WizardStep0_Activate(object sender, EventArgs e)
{
//Initialize dropdowns
PopulateRelationList(ddlRelation);
PopulateGuardianshipTypeList();
} //end method WizardStep0_Activate
Here are the two methods called in WizardStep0_Activate (the method BindSelectionListLocalized works elsewhere, so I know the problem isn't there):
protected void PopulateRelationList(DropDownList ddlist)
{
//First, clear the list
ddlist.Items.Clear();
string valueField = "RelationID";
string textField = "Relation";
string query = "SELECT CONVERT(nvarchar(2), RelationID) AS RelationID, Relation FROM tlkRelation WHERE Lang ='" + lang + "'";
DBFunctions.BindSelectionListLocalized(query, textField, valueField, ddlist, GetGlobalResourceObject("LocalizedText", "selectDDL").ToString());
} //end method PopulateRelationList
protected void PopulateGuardianshipTypeList()
{
//First, clear the list
cblGuardianshipType.Items.Clear();
string valueField = "GuardianshipType";
string textField = "TypeDescr";
string query = "SELECT GuardianshipType, TypeDescr FROM tlkGuardianshipTypes WHERE Lang = '" + lang + "'";
DBFunctions.BindSelectionListLocalized(query, textField, valueField, cblGuardianshipType, null);
}
Here's what I'm getting (just the two list controls mentioned above) - the "Type of Guardianship Requested" should have a CheckBoxList with four items next to it; the "Relation to Client" DropDownList should have several choices:
The most important information is that the same code works correctly in the Activate events for all subsequent WizardSteps, just not for WizardStep0. When I run this in the debugger, WizardStep0_Activate is firing, and the methods to populate the list controls are running; the offending controls are somehow being cleared afterwards, when the page is rendered.

Entity framework object context saves new entities that were not added

I have been working with Entity Framework (VS2010 Framework 4.0) in my proyect. I had some trouble with using a different object context per form. What I did then, was to create a object context in the Main Menu Form (stays opened) and everytime I create and show one form, I pass that object context to this new form. Example:
public partial class frm_Menu : Base
{
public Sistema_financiero_Entities db = new Sistema_financiero_Entities();
private void cancelarCuotaToolStripMenuItem_Click(object sender, EventArgs e)
{
frm_Cancelacion_Cuota Form1 = new frm_Cancelacion_Cuota();
Form1.db = db;
Form1.Show();
}
}
Ok, that solution worked fine until now because I needed to use and pass objects throw the differents forms sometimes, and if the objects contexts were different, I got an error.
Now, I have detected a huge issue using it this way. I have a form, where I can pay for the different installments of a loan. I´ll attach an image so then you can see what I´m talking about.
There, you select the different installments you want to pay for. Then, you introduce the value you will finally pay in "Total cobrado". Here is the important thing: When the checkbox image is checked (the blue one - already checked in the image), I create a "payment" entity per installment. Every "payment" object is stored in a list. If I uncheck it, I can change the value and the same thing is done. Obviously, I´m clearing the list before doing a list.Clear();. Then, one the checkbox checked, I can press "Aceptar" (accept). There I add to the database every "payment"(PAGO) in the list. After that, I save all changes.
foreach (Pago p in Lista_nuevos_pagos)
{
db.AddToPago(p);
}
try
{
db.SaveChanges();
this.Close();
}
My problem, is that it´s not only adding those "payments" in the list but the other "payments" entities that were in the list before clearing it. I reach the conclusion that when I clear the list, the objects remains in the object context. I thought that if the entity is not in the database, I have to Add it to the entity in the object context as I did with pago (db.AddToPago(p);).
I wanted to ask you guys how can I solve this issues. I solved it now doing this:
private void cancelarCuotaToolStripMenuItem_Click(object sender, EventArgs e)
{
Sistema_financiero_Entities db = new Sistema_financiero_Entities();
frm_Cancelacion_Cuota Form1 = new frm_Cancelacion_Cuota();
Form1.db = db;
Form1.Show();
}
Instead of creating just one global db for all forms, I create one in the Main Menu for every form. Then, in that form closed event, I dispose that object context.
Then, when i check the checkbox image, before creating the "payments", I delete every "Pago" entity from the object context:
foreach (Pago p in Lista_nuevos_pagos)
{
db.DeleteObject(p);
}
Lista_nuevos_pagos.Clear();
Doing this works correctly, but I´m still having trouble with some other created entities (Installments) that are not deleted when I clear a list. I think I´m doing it wrongly, thats why I need some direction to use EF correctly. I really need to get this done really soon, I don´t have too much time to read EF tutorials.
Just in case, this is how I create every "Pago" (payment)
Pago p = new Pago();
p.desc_aumento_intereses = nudwb1.Value;
p.desc_aumento_punitorios = nudwb2.Value;
p.desc_aumento_gastos = nudwb3.Value;
p.desc_aumento_comision = nudwb4.Value;
p.cotizacion = ntxt_Cotizacion.Value;
p.fecha_hora = fecha_hora;
Cuota c = new Cuota();
string name = tbx.Name.Substring(tbx.Name.IndexOf("-") + 1);
int nro_cuota = Convert.ToInt32(name);
c = Lista_cuotas_cobrar.Where(x => x.num_cuota == nro_cuota).First();
p.Cuota.Add(c);
Thank you for reading, I know this is a lot of info. Hope some guide soon..
I guess that you have references to those object in your Lista_nuevos_pagos list. This is why they will be duplicated.

C# how to show available data one by one in textbox

Hi I am using HtmlAgilityPack to scrap some data from web using c# . Here is the code :
private void button1_Click(object sender, EventArgs e)
{
var url = this.textBox1.Text;
var webGet = new HtmlWeb();
var document = webGet.Load(url);
var metaTags = document.DocumentNode.SelectNodes("//meta");
if (metaTags != null)
{
foreach (var tag in metaTags)
{
var name = tag.Attributes["name"].Value;
var content = tag.Attributes["content"].Value;
this.textBox2.Text = name + " : " + content;
}
}
}
its getting a link from textbox1 and showing the output to textbox2 . Its showing the last available data . I can concate the available data but it will show all data at once. Actually I want to show one data when it is available while others are being processed so that user can realize the scrapping progress.Would anyone please help ??
Assuming the first half of your code is correct, this will show the data one-by-one. Most likely, the foreach loop is executing too quickly for you to notice the "one-by-one" effect.
You could apply an artificial delay if you need to display each result long enough for someone to read. Maybe with a Timer or something similar.
An alternative is to use a multi-line textbox (for example a RichTextBox) and place each result on a new-line. Or a ComboBox, which won't take up as much room. These options allow you to keep the data, without having to overwrite it.
You can user Timer control to delay the display of next value in the loop.
You can also use BackgroundWorker to get this done. However this would add complexity to your code. Please look at Beginners Guide to Threading in .NET: Part 5
Or you can use Thread.Sleep(xx) which will delay the execution for the milliseconds you specify.
Thread.Sleep(2000);
this.textBox2.Text += name + " : " + content + Environment.NewLine;

Categories

Resources