Home > Backend Development > C++ > How to Pass Text Data Between Two Forms in C#?

How to Pass Text Data Between Two Forms in C#?

Susan Sarandon
Release: 2025-01-20 16:03:09
Original
387 people have browsed it

How to Pass Text Data Between Two Forms in C#?

Efficient Data Transfer Between C# Forms

Data exchange between forms is a frequent programming hurdle. This article addresses a developer's challenge in transferring text data between two C# forms.

The scenario involves Form1 (containing UI elements such as a listbox) and Form2 (with a textbox). The objective was to move the textbox text from Form2 to Form1's listbox.

A direct approach of making the listbox public in Form1 and directly adding text from Form2 failed.

A more robust solution involves modifying Form1's constructor to accept a parameter. This parameter receives the text data from Form2's textbox. The text is then added to the listbox during Form1's initialization.

<code class="language-csharp">public Form1(string customItem)
{
  InitializeComponent();
  this.myListBox.Items.Add(customItem);
}</code>
Copy after login

When creating an instance of Form1, the text is passed as an argument:

<code class="language-csharp">Form1 frm = new Form1(this.textBox.Text);</code>
Copy after login

This method ensures reliable data transfer between forms, providing a clean and effective solution.

The above is the detailed content of How to Pass Text Data Between Two Forms in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template