Windows Forms: How to Get value from another Form in C#
By FoxLearn 7/25/2017 9:49:06 PM 8.55K
How to get data from another form in c#
Step 1: Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "GetValueFromAnotherForm" and then click OK
Step 2: Design your form as below
Form1
frmAddEditStudent
Step 3: Create a student class to map data
public class Student { public string ID { get; set; } public string FullName { get; set; } }
Step 4: Add code to handle your form as below
Form1
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace GetValueFromAnotherForm { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnAdd_Click(object sender, EventArgs e) { //Add a student to binding source using(frmAddEditStudent frm = new frmAddEditStudent() { StudentInfo = new Student() }) { if (frm.ShowDialog() == DialogResult.OK) studentBindingSource.Add(frm.StudentInfo); } } private void btnEdit_Click(object sender, EventArgs e) { Student obj = studentBindingSource.Current as Student; if(obj != null) { using(frmAddEditStudent frm = new frmAddEditStudent() { StudentInfo = obj }) { if(frm.ShowDialog() == DialogResult.OK) { studentBindingSource.EndEdit(); btnEdit.Focus(); } } } } } }
frmAddEditStudent
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace GetValueFromAnotherForm { public partial class frmAddEditStudent : Form { public Student StudentInfo { get; set; } public frmAddEditStudent() { InitializeComponent(); } private void frmAddEditStudent_Load(object sender, EventArgs e) { //Init data if (StudentInfo != null) { txtStudentID.Text = StudentInfo.ID; txtFullName.Text = StudentInfo.FullName; } } private void btnOK_Click(object sender, EventArgs e) { StudentInfo.ID = txtStudentID.Text; StudentInfo.FullName = txtFullName.Text; } } }
VIDEO TUTORIALS
- How to Send and Receive email in Microsoft Outlook using C#
- How to Print Windows Form in C#
- How to Use Form Load and Button click Event in C#
- How to use Advanced Filter DataGridView in C#
- How to use TagListControl in C#
- How to use Error Provider in C#
- How to Drag and Drop controls in C#
- How to Create a Random Password Generator in C#
Categories
Popular Posts
How to Download Chromedriver for Selenium
08/29/2024
C# Tutorial
07/20/2024
How to Download Microsoft SQL Server
06/22/2024