Problems with reading Data from a Usercontrol - c#

I have the following Problem, i created a C# User Control with a couple of Input fields.
I implemented 2 Main functions ( Set_Data and Read_Data).
Set Data Reads some Data from a Class and Displays it at the User_Control.
Read_Data: Reads the Input value and stores it inside the same Class.
These functions are tested and work properly.
But if i try to use the same User Control to store the Data into another Instance of the same class the Information in the first Class stores the values of the second one too.
Maybe im just doing something wrong.
private Data_Class DataClass1 = new Data_Class();
private Data_Class DataClass2 = new Data_Class();
private void btn_page1_Click(object sender, EventArgs e)
{
page = "page1";
UserControl1.set_Data(DataClass1);
UserControl1.BringToFront();
}
private void btn_page2_Click(object sender, EventArgs e)
{
page = "page2";
UserControl1.set_Data(DataClass2);
UserControl1.BringToFront();
}
private void check_pagechange_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (page != last_page)
{
if (last_page == "page1")
{
DataClass1 = UserControl1.read_Data();
}
if (last_page == "page2")
{
DataClass2 = UserControl1.read_Data();
}
last_page = page;
}
}
As it can be seen i use a Backgroundworker which reads the Data from the Usercontrol when there is a Pagechange.

Related

Main form fields only display data of first item selected within listbox

I have two forms that need to interact with each other. The parent form has 4 fields and an add button that saves data from each field to an instance of a class object. After its saved to an object the object is stored in a listbox, which the child form contains. I created a custom event to handle that stuff, but I am surely doing something wrong.
What's supposed to happen is that when both windows are open, and there is data in the listbox, whatever item that is selected from the child form listbox fills the parent form fields with the data from that object. When I test out my code, only the first item has the data properly filling the correct fields. If I click any other item after the first selection, the main form fields do not update at all.
Specific to my issue the child form has the following codes:
public EventHandler ListBoxItemClicked;
private void pPotionList_SelectedIndexChanged(object sender, EventArgs e)
{
PotionForm tempMain = new PotionForm(); //this was a test, nothing changed
pPotionList.SelectionMode = SelectionMode.One;
if (ListBoxItemClicked != null)
{
ListBoxItemClicked(this, new EventArgs());
}
tempMain.Refresh(); // this too
}
The parent form has these codes
private void pListDisplay_Click(object sender, EventArgs e)
{
PotionList secForm = new PotionList();
secForm.secFormBox.DataSource = potionBindList;
PotionListChanged += secForm.HandlePotionListChanged;
secForm.ChildPotionListChanged += HandleChildPotionListChanged;
secForm.ListBoxItemClicked += HandleListBoxItemClicked; //this line
secForm.Show();
}
public void HandleListBoxItemClicked(object sender, EventArgs e)
{
pTypeInput.SelectedItem = aPotion._type;
pMagInput.Value = aPotion._magnitude;
pNameInput.Text = aPotion._name;
pBonusInput.Checked = aPotion._bonus;
}
I am currently using Visual Studio Community 2015 if that's relevant.
Ok after seeing all the necessary code I would say that the problem is that you never pass the values from the Child-Form to the Parent. Whenever the event HandleListBoxItemClicked is fired only the initial values of aPotion are written to the controls.
As a solution I would suggest to pass the SelectedItem as the sender when you fire the ListBoxItemClicked event in the childform:
CHILD
public EventHandler ListBoxItemClicked;
private void pPotionList_SelectedIndexChanged(object sender, EventArgs e)
{
Potion p = pPotionList.SelectedItem as Potion;
pPotionList.SelectionMode = SelectionMode.One;
if (p != null)
{
if (ListBoxItemClicked != null)
{
ListBoxItemClicked(p, new EventArgs());
}
}
}
Not you can use this information in the parent form and disperse the information as you please:
PARENT
public void HandleListBoxItemClicked(object sender, EventArgs e)
{
Potion p_parent = sender as Potion;
if(p_parent != null)
{
pTypeInput.SelectedItem = p_parent._type;
pMagInput.Value = p_parent._magnitude;
pNameInput.Text = p_parent._name;
pBonusInput.Checked = p_parent._bonus;
}
}
No refresh or anything else should now be necessary. Hope it helps

Passing data between C# forms

I am struggling to pass data between two forms (all I want to do is have a textbox in Form1, and show that textbox value in textbox1, which is located in Form2). How would I go about this, using WPF? Have looked at quite a few solutions, but cannot seem to get any of them at all to work.
For the form in which I'm wanting to display the values (in tbd.Text), here is the code:
namespace test
{
/// <summary>
/// Interaction logic for OptionDisplayWindow.xaml
/// </summary>
public partial class OptionDisplayWindow : Window
{
public OptionDisplayWindow()
{
InitializeComponent();
tbd.Text = "k"; //want to change this value based on "s" in the other form
}
The form in which the text is transferred from (want to display the string):
public void Button1_Click(object sender, RoutedEventArgs e)
{
string s = "testText"
}
I have tried every single other answer on SO (spent the past 6 hours trying) and have had absolutely no luck.
EDIT 2: Using the method listed as the best answer here Send values from one form to another form I've come up with this code for Form1:
private void ttbtn_Click(object sender, RoutedEventArgs e)
{
using (Form2 form2 = new Form2())
{
tbd.Text = form2.TheValue;
}
}
And the code for Form2:
public string TheValue
{
get { return arrayTest.Text; }
}
However, I'm getting the error 'Form 2': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
The code that you put in the sample project (that you provided as a link in the comments) should be in your question. Given that it becomes much easier to understand what you're trying to do and to give you a workable solution.
I would suggest creating a "DataTransferObject" and pass that between each form.
public class Dto
{
public string Text;
}
The code in MainWindow would then look like this:
private void button1_Click(object sender, RoutedEventArgs e)
{
var dto = new Dto();
window2 win2 = new window2();
win2.Dto = dto;
win2.ShowDialog();
textBox1.Text = dto.Text;
}
And the code in window2 would look like this:
public Dto Dto;
private void textBox2_TextChanged(object sender, TextChangedEventArgs e)
{
if (this.Dto != null)
{
this.Dto.Text = textBox2.Text;
}
}
That is one way - out of about a million - of transferring data between forms. An advantage of using a data transfer object is that it begins you on the road of separating your data from your UI, and that is generally a very good thing to do.
Another simple way to pass data between forms is using your application's settings.
Step 1: Create a setting, open the "Project" menu and pick "test Properties..."
this will take you to the settings page, create a setting name it however you want, I named mine "PassString" and make sure it's a string type and the Scope is set to user.
Step 2. Lets set the string setting to your textbox.text property, add these changes to the code:
private void button1_Click(object sender, RoutedEventArgs e)
{
Properties.Settings.Default.PassString = textBox1.Text;
window2 win2 = new window2();
win2.ShowDialog();
}
Step 3. Update the text on your second window Initialization Process.
public OptionDisplayWindow()
{
InitializeComponent();
tbd.Text = Properties.Settings.Default.PassString;
}
P.S. you may have to add a reference to reach your application settings.
using test.Properties;

System.FormatException occurred in mscorlib.dll when converting it int32

I know, i know there are lots and lots of questions asking on here about this error, each with their own response, but its easier to work off a response regarding your own code rather than someone else's
I have been working on this program for some time for a college assignment, and as soon as i started putting in the class to calculate the totals of things it now crashes,
I don't know where to look so i'll post my main code
enter code here
namespace Till
public partial class MainWindow : Window
{
Calculator calc = new Calculator();
public MainWindow()
{
InitializeComponent();
}
public bool User;
public bool tillopen = false;
private void button_Click(object sender, RoutedEventArgs e)
{
//button clone thingy
Button btn = (Button)sender;
label.Content = label.Content + btn.Content.ToString();
Console.Beep(); // makes the buttons beep
}
private void clear_Click(object sender, RoutedEventArgs e)
{
// Clear
label.Content = "";
}
private void Button_Submit_Click(object sender, RoutedEventArgs e)
{
// submit
listView.Items.Add(label.Content);
label.Content = "";
calc.setSoldItems(Convert.ToInt32(label.Content)); /// it breaks on this line///
}
private void button13_Click(object sender, RoutedEventArgs e)
{
//void sale
label.Content = "";
listView.Items.Clear();
}
private void button15_Click(object sender, RoutedEventArgs e)
{
//pound
label.Content = "1.00";
}
private void button12_Click(object sender, RoutedEventArgs e)
{
//till open close
tillopen = true;
}
private void button16_Click(object sender, RoutedEventArgs e)
{
Login m = new Login();
m.Show();
this.Close();
}
private void button14_Click(object sender, RoutedEventArgs e)
{
label.Content = "2.00"; // 2 pound
}
private void button17_Click(object sender, RoutedEventArgs e)
{
label.Content = calc.finish();
}
}
I have tried to re-create the error in another WPF (converting a to an int32) and it works fine, i know this is an issue with my code itself, i have tried using other machine and using different versions of visual studio itself, so we came to the assumption its this code itself and not a broken dll file
So before I sit down with my Teacher and spend all day going though my code step by step im asking around for help in order to save both of our time, This assignment is due in in 3 weeks, and it decides to break on me now.
thankies
To replicate this error, i press a number button on my Windows form, them hit the submit button i created (which starts the conversion) If a copy of my class which handles all of this is needed im happy to post it
In the method button_click, you have assigned value as
label.Content = label.Content + btn.Content.ToString();
which is a string value to the label and the values are concatenated instead of add.
and when you are reading it, you are converting it in Int32. which will give exception as it will not contain any integer value to it.
You can add the value like this:
label.Content = (Convert.ToInt32(label.Content) + Convert.ToInt32(btn.Content)).ToString();
and check before converting if the label has blank values in it, if it has do not convert them, and only convert the value if it has some values it will not give any error. Also do not assign any values other that numerical digits.
You are calculating:
Convert.ToInt32(label.Content)
but on the line before you set:
label.Content = "";
so this means you are calculating
Convert.ToInt32("")
which gives you a FormatException.
Perhaps you should use the value of label.Content before you overwrite it?

Asp.net c# : ListBox showing only one item

I've this program with two web forms. I take the data from one of the web forms through
public GigOpportunity GetData()
{
//Get written data from text boxes from this web form to the other
return new GigOpportunity(txtBoxID.Text, Calendar1.SelectedDate.Date,
TextBoxVenue.Text, TextBoxGenre.Text, Convert.ToDouble(TextBoxCost.Text),
Convert.ToInt32(TextBoxCapacity.Text), CheckHeadLiner.Checked,
TextBoxMainAct.Text, CheckEngineer.Checked);
}
public void ButtonOk_Click(object sender, EventArgs e)
{
// First part: Saves info on first page.
Session.Add("Gig", GetData());
// First part: Saves info on first page.
GigManagerWebForm.add = true;
Server.Transfer("~/GigManagerWebForm.aspx");
}
And I get it to another form through this,
private void Page_Load(object sender, EventArgs e)
{
gigList = new GigList();
AddGig();
}
private void UpdateList()
{
lstGigs.Items.Clear();
for (int i = 0; i < gigList.Count(); i++)
{
lstGigs.Items.Add(Convert.ToString(gigList.getGig(i)));
}
}
public void AddGig()
{
if (add == true)
{
//Reads info into variables on the second page.
GigOpportunity getData = (GigOpportunity)(Session["Gig"]);
gigList.addGig(getData);
add = false;
//Create new session ID
Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
}
UpdateList();
}
I simply have no clue why my list only shows me the one item that I lastly add.
In Page_Load you initalize a new GigList to the gigList variable. In AddGig you add a new GigOpportunity to it.
Then in UpdateList, you clear the lstGigs, and add whatever is in gigList to it. There's only one item in gigList, which is the one you just added. That's the reason you're only seeing the last item.
Where and how is lstGigs initialized? It should be populated from some kind of storage before you try to add the new item.
This is because in UpdateList method you clears out the list and you add elements from gigList but on every Page_Load gigList becames new List and addGig adds to it only one item. To resolve the issue you have you probably ought to not clear the ListBox before you add new element. Alternatively you might want to store whole list (not only last added element) in a session. You might as well save that List to ViewState.
I tried the following simplified code on my application and it worked:
public void ButtonOk_Click(object sender, EventArgs e)
{
// First part: Saves info on first page.
if (Session["Gig"] == null)
{
Session.Add("Gig", new List<string>());
}
List<string> list = (List<string>)Session["Gig"];
list.Add("new Data");
Session["Gig"] = list;
Server.Transfer("~/GigManagerWebForm.aspx");
}
// On the GigManagerWebForm.aspx
private void Page_Load(object sender, EventArgs e)
{
AddGig();
}
public void AddGig()
{
if(Session["Gig"] != null)
{
//Reads info into variables on the second page.
List<string> getData = (List<string>)(Session["Gig"]);
ListBox1.Items.AddRange(getData.Select(d => new ListItem(d)).ToArray());
Session["Gig"] = getData;
}
}

Making two boxes equal each other

I am trying to make a text box (UPC_txtBox4) self populate to equal the same value of UPC_txtBox2. The two text boxes are on separate forms but I feel there should be a way to link the two.
If form1 is responsible for navigating to form2, then you can pass the value on the query string from form1 using a URL similar to the following:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
Response.Redirect(Request.ApplicationPath + "/Form2.aspx?upc=" + UPC_txtBox2.Text, false);
}
}
then in form2 code:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// Assuming this field is an asp.net textbox and not an HTML input
UPC_txtBox4.Text = Request.QueryString["upc"];
}
}
Alternatively, you could store the value in session state, assuming that you are using sessions.
CORRECTION: Seeing as you are using WebForms, not WinForms as I had assumed, the below is irrelevant. I'll leave it just incase it helps someone else.
You should just create a method on the form that needs to be updated, then pass a reference when of that form to the newly created form.
This won't work if either form is a dialog (as far as I know).
So:
Form that has the textbox that will be directly edited.
private Form formToUpdate;
public void OpenForm(Form _formToUpdate)
{
formToUpdate = _formToUpdate;
txtBlah.TextChanged += new EventHandler(OnTextChanged);
this.Show();
}
private void OnTextChanged(object sender, EventArgs e)
{
formToUpdate.UpdateText(txtBlah.Text);
}
Form that is to be dynamically updated:
delegate void StringParameterDelegate (string value);
public void UpdateText(string textToUpdate)
{
if (InvokeRequired)
{
BeginInvoke(new StringParameterDelegate(UpdateText), new object[]{textToUpdate});
return;
}
// Must be on the UI thread if we've got this far
txtblah2.Text = textToUpdate;
}
Note: this is untested (although it should work), and largely pseudo code, you'll need to tailor it to your solution obviously.

Categories