Making two boxes equal each other - c#

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.

Related

Winform copy button text to textbox using universal method

So this is a fairly straightforward thing, and I am just curious if there is a better way to do it to save lines of code. For class we are making a teletype machine. Basically there is a textbox, and a series of buttons A-Z and 0-9. When you click the button it adds the corresponding letter/number to the textbox. When you click send, it adds the contents of the textbox to a label and resets the textbox. Everything works and it only took a few minutes to build. However there is a mess of redundant lines and I was curious if there is a way to clean up the code with a method.
This is my current code.
private void btn_A_Click(object sender, EventArgs e)
{
box_UserInput.Text = box_UserInput.Text + "A";
}
As you can see, it is very simplistic and straight forward. Click A, and "A" gets added to the textbox. However the Text property of the button is also just "A" and I want to know if there is a way to just copy the text property of that button and add it to the textbox string.
Something like this, except with a universal approach where instead of having to specify btn_A it just inherits which button to copy based on the button clicked. That way I can use the same line of code on every button.
private void btn_A_Click(object sender, EventArgs e)
{
box_UserInput.Text = box_UserInput.Text + btn_A.Text;
}
You can use this which is more universal as the Control class contains the Text property. Also, using the best practice $"".
private void btn_A_Click(object sender, EventArgs e)
{
box_UserInput.Text = $"{box_UserInput.Text}{((Control)sender).Text}";
}
You can also assign the same event to each button. Create an event, say addControlTextOnClick and assign the same event to each button.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addControlTextOnClick(object sender, EventArgs e)
{
box_UserInput.Text = $"{box_UserInput.Text}{((Control)sender).Text}";
}
}
You can even shorten this more using this C# construct:
private void addControlTextOnClick(object sender, EventArgs e) =>
box_UserInput.Text = $"{box_UserInput.Text}{((Control)sender).Text}";

C# open a Form and close it

I want to show a Form called TTT so I tried this:
public static TTT ttt_local = new TTT();
private void button1_Click(object sender, EventArgs e)
{
ttt_local.Show();
}
Then I want to close the Form from inside so ttt_local closes itself when a button in ttt_local is pressed. That works but if I want to reopen ttt_local I get an ObjectDisposedException. Can someone help me please?
You should not need to let a form close itself, however you can set its visibility or simply hide it (the same also applies for showing a form):
Consumer-code:
var ttt = new TTT();
ttt.Show();
TTT-class:
public class TTT : Form
{
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
}
}
Now call ttt.Show() again within your consumer-code, not the form-class itself.
Alternativly you may set the visibility of the form using Form.Visibility.
You have two options.
Use instance variable instead of class variable and let the things work as it is now.
Don't dispose the form, just live with Show/Hide options.
.
Option 1:
public TTT ttt_local = new TTT();
private void button1_Click(object sender, EventArgs e)
{
if(ttt_local == null) ttt_local = new TTT();
ttt_local.Show();
}
Option 2:
Don't close the form, just play with hide/show or even set the Visible property.
What is the reason of using a global variable? You should only put the variable definition inside the event function:
private void button1_Click(object sender, EventArgs e)
{
TTT ttt_local = new TTT();
ttt_local.Show();
}
Whenever the event is triggered, the variable creates and then it disposes with closing the form.
You can show it and then hide it like that:
ttt_local.Show();
ttt_local.Hide();
or close:
ttt_local.Close();
Regards.

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;

Why does my variable lose its value?

From the selectedindexchanged event, my variable has a value, but when it reaches the btn_click() event, the variable no longer has a value. Why is that?
public partial class TestingDatapass
{
private string item = null;
private string itemprice = null;
private int totalprice = 0;
protected void item_selectedindexchanged(object sender, EventArgs e)
{
//Both have a value here
item = item.SelectedValue;
itemprice = item.SelectedValue.Text;
}
protected void btn_click(object sender, EventArgs e)
{
//no value here
totalprice = Convert.ToInt32(itemprice)*Convert.ToInt32(item);
MessageBox.Show(totalprice);
}
}
EDIT
And to answer the ? posed in comments, the order of occurrence is the selectedindexchange THEN the btn_click()
EDIT REGARDING View State
So then would this be a proper way to set up what I am trying to achieve?
public partial class TestingDatapass
{
private int totalprice = 0;
protected void item_selectedindexchanged(object sender, EventArgs e)
{
ViewState["item"] = item.SelectedValue;
ViewState["itemprice"] = item.SelectedValue.Text;
}
protected void btn_click(object sender, EventArgs e)
{
totalprice = Convert.ToInt32(ViewState["item"])*Convert.ToInt32(ViewState["itemprice"]);
}
}
When a page is requested, ASP.NET creates an instance of TestingDatapass class and initialize itemprice,totalprice etc. fields. Now when you change your dropdown from client (which I assume looking at your item_selectedindexchanged method), Postback happens and it assign values you have mentioned in item_selectedindexchanged. Finally it destroys the instance, generates the html and sends it back to browser.
Now, when you press the button in your page then a new instance is created, your fields are re-initialized and you don't see the changed values in btn_click. This is how it works.
Thus if you want to preserve any data across postback, Consider using any State Management technique like ViewState, HiddenField etc.
Also, as a side note, MessageBox.Show is not available in ASP.NET.
Update:
I answered in the context of why it is not retaining the value in button click event, there are many ways to do it. But to answer your question, I don't see any reason to store the values in item_selectedindexchanged event as you are not doing anything there. You can directly access the dropdown selected values in button click handler like this:-
protected void btn_click(object sender, EventArgs e)
{
totalprice = Convert.ToInt32(item.SelectedValue) *
Convert.ToInt32(item.SelectedItem.Text);
}
Also, please note it's item.SelectedItem.Text and not SelectedValue.Text.

Windows form opening other forms

What I want
I am creating an application which has two functionalities. Both functionalities have their own form (called FactuurForm and VerhuurForm). I have another Form called Home, which has, among others, two buttons. Depending on which button is clicked, I wish to open one of the two forms, and complete close the Home-form.
What I have
Currently, I have the following code:
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Home home = new Home();
home.ShowDialog();
if (home.kiesFactuur)
{
FactuurForm factuur = new FactuurForm();
home.Close();
factuur.ShowDialog();
}
else if (home.kiesVerhuur)
{
VerhuurForm verhuur = new VerhuurForm();
home.Close();
verhuur.ShowDialog();
}
}
}
kiesFactuur and kiesVerhuur are booleans which in my Home class, initialized as false. As soon as I click on of the buttons, the corresponding boolean will flip to true, triggering the if-statements to close the home-form and open the new form.
My question
Altough my current codes works, it seems a bit much for such a simple functionality. I feel like I wouldn't need the booleans and this go all be done easier. So is there an easier/better way to do this?
I've also thought about creating multiple Main functions. Clicking a button would activate the corresponding new Main function and terminate the current Main. Is this even possible and if so, is it a good solution?
I don't exactly understand the need to completely close the home form. I'd just place 2 eventhandlers for each of the buttons and call the following code on them. The first form will be hidden and closed when you close your subform.
private void ShowSubDialog(Form form)
{
this.Hide(); //makes your main form invisible before showing the subform
form.ShowDialog();
}
private void button1_Click(object sender, EventArgs e)
{
ShowSubDialog(new FactuurForm());
Dispose();
}
private void button2_Click(object sender, EventArgs e)
{
ShowSubDialog(new VerhuurForm());
Dispose();
}
private void Factuur_Click(object sender, EventArgs e) {
LoadForm(new FactuurForm());
}
private void Verhuur_Click(object sender, EventArgs e) {
LoadForm(new VerhuurForm());
}
private void LoadForm(Form f) {
this.Hide();
f.ShowDialog();
this.Show();
}
Add this to your Home form, remove everything after home.ShowDialog() from Main, and make Facturr_Click and Verhurr_Click handle their respective button's click events. This will allow Home to hide/show automatically.
You should replace your code like this :
if (home.kiesFactuur)
{
FactuurForm factuur = new FactuurForm();
factuur.Show();
this.Hide();
}
else if (home.kiesVerhuur)
{
VerhuurForm verhuur = new VerhuurForm();
verhuur .Show();
this.Hide();
}
In the VerhuurForm and FactuurForm you may ovveride the event of closure like this :
public VerhuurForm()
{
InitializeComponent();
this.FormClosed += new FormClosedEventHandler(VerhuurForm_FormClosed);
}
void FormClosedEventHandler(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
To be sure that your application is closed if you close the form because the Home still active but hidden.

Categories