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
Susan SarandonOriginal
2025-01-20 16:03:09387browse

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>

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>

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!

Statement:
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