Copy paste from one form to other c# - c#

What im trying to do:
Search products by BarCode on Form1 form;
if it cannot be found:
1. Open Inventory form
2. Search product by name or description
3. On ListView click on the found product copy its BarCode and paste it to the Form1 barcode textbox.
All that is done corectly. The problem is that every time I add product from Inventory form a new Form1 is opened.
The values are not processed in the same Form1, so assume I sell 4 products:
2 of them are added through Form1 barcode search
2 of them are added through Inventory search form
In the end I get 3 opened Form1 forms, one with 2 products and two forms with single product (added through Inventory form). I need them to be all in one.
Thanks
//-------------------------Form1--------------------------------------------
private void btnInventory_Click(object sender, EventArgs e)
{
Inventory Inventory = new Inventory();
Inventory.Show();
}
private string _theValue;
public string TheValue
{
get
{
return _theValue;
}
set
{
_theValue = value;
txtItems.Text = value;
}
}
//-----------------------------Inventory---------------------------------
private void ShowForm1()
{
string value = label9.Text;
Form1 newForm = new Form1();
newForm.TheValue = value;
this.Close();
newForm.ShowDialog();
}
private void lvList_Click(object sender, EventArgs e)
{
label9.Text = lvList.SelectedItems[0].SubItems[0].Text;
this.ShowForm1();
}
Im sorry for the delay, i had to wait 8h before posting again
Thanks for ur reply.
I just tried that
Form1
private void btnInventory_Click(object sender, EventArgs e)
{
Inventory _inv = new Inventory();
if (DialogResult.OK == _inv.ShowDialog())
{
txtItems.Text = _inv.fugi;
}
}
and in Inventory Form
private string test;
public string fugi
{
get { return test; }
set { test = label9.Text; }
}
private void lvList_Click(object sender, EventArgs e)
{
label9.Text = lvList.SelectedItems[0].SubItems[0].Text;
this.DialogResult = DialogResult.OK;
this.Close();
}
txtItems.Text does not get the value of test from inventory form

Its opening a new dialog because you tell it to in ShowForm1, Personally I would change your btnInventory click as follows
private void btnInventory_Click(object sender, EventArgs e)
{
Inventory _inv = new Inventory();
if(DialogResult.OK == Inventory.ShowDialog())
{
valueIWantToSet = _inv.Accessor;
}
}
Accessor you will need to make yourself similar to
public TypeOfVar Accessor
{
get{return m_privateVariableThatIWillMakeAndSetToMyBarcode;}
}
Edit:
Once you have gotten the value of your barcode you need to set DialogResult as Follows
this.DialogResult = DialogResult.OK;
and then set the variable you wish to access to the barcode before closing your form
Edit2:
Your ShowForm1 will end up similar to this (May want to rename this method!)
{
this.DialogResult = DialogResult.OK;
m_myVar = SelectedItem..;
this.Close;
}
UPDATE ANSWER
You are still having problems as you haven't used the set property correctly, your get is fine as it is. There is a keyword in c# called value that should be used for setters. this value will take the value of whatever is on the right hand side of an = sign.. you can think of it like this...
fugi = label9.Text
In the above line, fugi is using your properties getter in order to get the value that needs to be set to label9.Text. The = sign says that you intend to use the setter for this property and set the value of value to label9.Text.
Properties with a getter and setter are used so you do not have to provide access to the underlying variable to somewhere you would not like to and then can have the option to just set or get this variable as needed.
This means that your problem persists have you have yet to set the value of test, it is still the default string value.
So you have a couple of ways to solve your problem.
The first way is just to provide a getter for label9.Text and remove the need for your private variable.
public string Fugi //Properties should really start with capital letter
{
get{return label9.Text;}
}
The second is to set the value of test before you call your getter in btnInventoryClick and remove the setter method
private void lvList_Click(object sender, EventArgs e)
{
test = label9.Text;
and the third ist to set test as shown in method 2 but also change the set method of Fugi to the following to allow this test variable to be set elsewhere.
set{text = value;}

Related

C# communication between forms bug

I'm working on a GUI for an admin interface for management of a student complex. Currently the GUI has a listbox with predefined 6 rules for the students. In the beginning of the code, I add them to a list
private void Form1_Load(object sender, EventArgs e)
{
foreach (string rule in lbRules.Items)
ruleList.Add(rule);
}
Then, the GUI provides the admin with an option to modify the rules. To do so he selects a rule from the listbox and clicks a "Modify" button, which opens another form:
private void BtnModify_Click(object sender, EventArgs e)
{
if (lbRules.SelectedItems.Count > 0)
{
selectedRule = lbRules.SelectedItem.ToString();
selectedIndex = lbRules.SelectedIndex;
selectedRuleNumber = selectedRule.Substring(0, 3);
selectedRule = selectedRule.Substring(6);
var rulesForm = new Rules();
rulesForm.Show();
}
}
On the second form load event I get the rule's text and number:
private void Rules_Load(object sender, EventArgs e)
{
tbRule.Text = Form1.selectedRuleNumber;
tbModifyRule.Text = Form1.selectedRule;
}
The text gets added to a RichTextBox, from where the rule can be edited.
Then the admin clicks a "Save" button, which gets the edited text from the RichTextBox(tbModifyRule) and adds it to a static ruleList in form1, sets a static boolean from form1 to true. Afterwards the second form gets closed:
private void BtnSave_Click(object sender, EventArgs e)
{
saveRule = Form1.selectedRuleNumber + " - " + tbModifyRule.Text;
Form1.ruleList.Insert(Form1.selectedIndex, saveRule);
Form1.ruleList.RemoveAt(Form1.selectedIndex+1);
Form1.formOpen = true;
this.Dispose();
}
At this point we are back to form1, in which we have a timer with timer_tick event. In there we check whether the boolean formOpen is true (which it is set before closing form2). Inside the if statement we clear the listbox and add each rule from the ruleList (previously edited in form2) to the listbox, then sets the formOpen back to false so it doesn't get executed all the time:
if (formOpen)
{
lbRules.Items.Clear();
foreach (string item in ruleList)
lbRules.Items.Add(item);
}
formOpen = false;
Now this is really weird, and at this point makes absolutely no sense to me, since I tried debugging it for over an hour, trying different ways, which also led me to mysterious wonders of WHY TF IT WORKS WHENEVER IT WANTS...
So this works randomly, like it would work the first time, the second and third times it won't. Or vice versa. It's all random.
Strangely, I tried adding a breakpoint on the
lbRules.Items.Add(item);
in the foreach loop, so it stops on each item. And I actually saw the changed rule getting added from the ruleList into the listBox, however in the end it was not there.
And weirdly enough, I also tried adding the text from form2 in the listBox in form1, without using a list, but for whatever odd reason, I use the int selectedIndex, which gets the index of the selected item from the BtnModify_Click event to insert the text in that particular index, but this very index gets RANDOMLY set to bloody 0 after form2 closes.
hence, it again works from time to time, because at some tries it doesn't get set to 0 and it works.
if (formOpen)
{
selectedRule = Rules.saveRule;
lbRules.Items.Insert(selectedIndex, selectedRule);
lbRules.Items.RemoveAt(selectedIndex+1);
}
formOpen = false;
I don't assign value to this integer ANYWHERE else in the code.
I really tried digging some sense, but I hit a solid hard rock.
Any help appreciated!
And thanks for the time!
edit1:
as requested - rest of the timer method
private void Timer1_Tick(object sender, EventArgs e)
{
foreach (string text in ws.messages)
message = text;
if (ws.messages.Count > 0)
{
if (message.Contains("comp"))
{
Complaints();
message = String.Empty;
ws.messages.Clear();
}
}
if (formOpen)
{
lbRules.Items.Clear();
foreach (string item in ruleList)
lbRules.Items.Add(item);
}
formOpen = false;
}
I would change your code to the following:
if (formOpen)
{
formOpen = false;
lbRules.Items.Clear();
foreach (string item in ruleList)
lbRules.Items.Add(item);
}
The issue with having the formOpen = false; outside the if statement is that there is a chance that once the user clicks the Save button the timer could be about to execute the formOpen = false instruction setting it to false making the code inside the If statement to never be executed.
I truly believe this is not random but just a timing issue due to complicated logic.
If I were you, I'd do a couple things:
Use a separate class for data exchange between forms, avoid using public static (I assume) form members for this.
Instead of a timer, subscribe to the Form.Closed event of RulesForm
This might make code flow a bit more predictable and allow you to find errors more easily.
Better yet, use the following pattern:
class Form1
{
private void BtnModify_Click(object sender, EventArgs e)
{
var ruleData = ..... //get current rule data
var rulesForm = new Rules();
rulesForm.SetData(ruleData); //pass initial state to the form
rulesForm.SaveChanges = this.ApplyRules; //pass a method which will be called on save
rulesForm.Show();
}
private bool ApplyRules(RuleData ruleData)
{
//do whatever you like with the rules here
return true;
}
}
class RuleForm
{
public void SetData(RuleData ruleData)
{
//initialize fields, etc
}
public Func<RuleData, bool> SaveChanges { get; set; }
private void BtnSave_Click(object sender, EventArgs e)
{
var ruleData = .... //get data from form fields
if(this.SaveChanges(ruleData))
this.Close();
}
}
class RuleData
{
//whatever data you need
}

How to add a text to CheckBox from form2 to form 1 (C#)

So, I've just started learning C# and I have been looking on tutorials in YouTube but in Console Applications.
I have now made my first WFA and I'm trying to create a Calendar where you can add different times with different texts so you stay informed for example a upcoming test.
So far I've come this far: It's in Swedish
And I've also connected the "Lägg Till" (Add in English) to another form called laggTill
Connection in codeform -
laggTill lgtl = new laggTill ();
lgtl.Show ();
Form2 called laggTill looks like:
Also in Swedish
So my question is, how can I by pressing the "Spara" button (Save in English) put the text from the TextBox in laggTill form to the CheckBox in the "Kommande datum:" CheckBox?
Create public properties in Form2, in the example below you can see how to access them.
you did not asked that, but sometimes you dont want to update Form1 (for example the user pressed on cancel button) - use the DialogResult value of Form 2 in order to determine if there is a need to update Form1, in the example DialogResult is DialogResult.OK but it could be also DialogResult.Cancel.
user presses "Spara" button on Form2:
public string valueToForm1 { get; set; } //public properties to access from form1
public DateTime value2ToForm1 { get; set; }
private void button1_Click(object sender, EventArgs e)
{
this.valueToForm1 = "SomeValue";
this.value2ToForm1 = dateTimePicker1.Value;
this.DialogResult = DialogResult.OK;
this.Close();
}
calling Form2 from Form1:
private void button1_Click(object sender, EventArgs e)
{
using (var form = new Form2())
{
var result = form.ShowDialog();
if (result == DialogResult.OK)
{
//values preserved after close
string val = form.valueToForm1;
DateTime dateValue = form.value2ToForm1;
//for example
this.txtValueFromForm2.Text = val;
this.dateTimePicker1.Value = dateValue;
}
}
}
on another button on Form2 (lets say cancel button) you can do that piece of code, if there is a case that you dont want to update Form1:
private void button2_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}

How to update label's value in the WindowsForms

In my program on the WindowsForms I have two forms: parent and child. In the child form I've changed the value of the variable, which was declared in the independent class.
When I'm closing the child form, I need to display a new value of the variable in the label of parent form, but I can see only old value. How to update it?
Here how I'm displaying it in the constructor of the parent form:
label6.Text = indicators.Money + "$";
Edit1:
Can't understand, why it doesn't update. Code in the parent form:
private void button3_Click(object sender, EventArgs e)
{
Computer computer = new Computer();
computer.ShowDialog();
label6.Refresh();
}
Edit2
Here what I've done. I'm still experimenting with what you advised:
private void button3_Click(object sender, EventArgs e)
{
Computer computer = new Computer();
Code.Indicators indicators = new Code.Indicators();
if (computer.ShowDialog() == DialogResult.OK)
label6.Text = indicators.Money.ToString();
label6.Refresh();
}
Actually what I need:
Try the Control.Refresh Method like this:
label6.Refresh();
Edit Per Update
The real issue here is your approach. Here is a pretty simple way of returning a value from a child form which is what you want.
Add a property to your your child form which you can use to access the Money amount set from the parent form.
public partial class YourChildForm : Form
{
public string YourMoney { get; private set; }
// The rest of your form code
}
Sample usage:
var childForm = new YourChildForm();
childForm.ShowDialog();
label6.Text = childForm.YourMoney;
Since you are stating your are using ShowDialog you can read the value out of your Child form right after you return from the ShowDialog Method. As I stated in the comments I would just create a Public property to set and get the value of your variable.
Try something like this:
child.CurrentIndicator = indicators;
if(child.ShowDialog == DialogResult.OK)
indicators = child.CurrentIndicator;
label6.Text = indicators.Money;
create property in your child form something like this;
public Indicator CurrentIndicator {get; set;} //You can use automatic properties or have a backing variable

Passing a class value from listbox in form1 to textbox in form2

I've just about got this but I'm not doing something right. I'm trying to pass a value from form1 to form2. On form2 I've got a property set up allowing access to one of it's text boxes. On form1 I've got it set to open an instance of form2 and pass a value from an object in a listbox to form2's text box. It seems like I've got things set up almost right because I tested it by posting the object value in a messagebox.show and it displayed the different object values just how I planned. For some reason though when I actually run it form2 will open but it will not set the value I passed to the textbox in the form, it's just a blank form. I've got no errors but I'm thinking it has something to do with the data not being passed directly to my new instance of form2. I hope I explained it well enough. Any help is appreciated.
form 1
private void propertiesToolStripMenuItem_Click(object sender, EventArgs e)
{
frmProperties editProperties = new frmProperties();
editProperties.ShowDialog();
Employee person = (Employee)lstBoxEmployees.Items[lstBoxEmployees.SelectedIndex];
editProperties.TextFirstName = person.EmployeeFirstName;
}
form 2
public string TextFirstName
{
get { return txtFirstName.Text; }
set { txtFirstName.Text = value; }
}
You have to set the textbox before you show the dialog.
private void propertiesToolStripMenuItem_Click(object sender, EventArgs e)
{
frmProperties editProperties = new frmProperties();
Employee person = (Employee)lstBoxEmployees.Items[lstBoxEmployees.SelectedIndex];
editProperties.TextFirstName = person.EmployeeFirstName;
editProperties.ShowDialog();
}
private void propertiesToolStripMenuItem_Click(object sender, EventArgs e)
{
frmProperties editProperties = new frmProperties();
editProperties.ShowDialog();
Employee person = new Employee ();
person.EmployeeFirstName = lstBoxEmployees.Items[lstBoxEmployees.SelectedIndex];
editProperties.TextFirstName = person.EmployeeFirstName;
}

passing variables into another form

I am developing a windows app in c#. I have used three decimal variables: counter, narrow, and broad which store different values based on some calculations.
On clicking a button, a message box is displayed showing these three decimal values and then the application exits..
Now I want to add another form having three labels in which these variable values needs to be shown. Please explain, how can I pass those variables in the next form to display in individual labels?
One method is to create a new constructor in the 2nd form. THen you can use those values from the 2nd form.
public Form2(decimal x, decimal y, decimal z):this()
{
this.TextBox1.Text = Convert.ToString(x);
this.Label1.Text = Convert.ToString(y);
etc...
};
From main form
Form2 frm2 = new Form2(x,y,z);
frm2.Show();
Create a new Form...
public class CalculationResultForm : Form
{
public CalculationResultForm(){}
public decimal Counter
{
set { labelCounter.Text = value.ToString(); }
}
public decimal Broad
{
set { labelBroad.Text = value.ToString(); }
}
public decimal Narrow
{
set { labelNarrow.Text = value.ToString(); }
}
private void OkButton_Click(object sender, EventArgs e)
{
// This will close the form (same as clicking ok on the message box)
DialogResult = DialogResult.OK;
}
}
Then within your existing form button click handler...
private void MyButton_Click(object sender, EventArgs e)
{
CalculationResultForm resultForm = new CalculationResultForm();
resultForm.Counter = _counter;
resultForm.Narrow = _narrow;
resultForm.Broad = _broad;
resultForm .ShowDialog();
Application.Exit();
}
The easiest way is to probably add a new method, lets call it ShowWithDetails:
public void ShowWithDetails(double Counter, double Narrow, double Broad)
{
CounterLabel.Text = Counter.ToString();
NarrowLabel.Text = Narrow.ToString();
BroadLabel.Text = Broad.ToString();
ShowDialog();
}
An easy way is to use properties. The form you want to pass the values to is just another class.
add something like this to the second form:
public int counter {get; set;}
then from the first form you'd do something along the lines of
Form2 form2 = new Form2();
form2.counter = 1;
form2.ShowDialog();
or something along those lines.
There is a blog post describing how to do this without using ShowDialog().

Categories