如何在C#窗体中将值从控件传递到另一个控件 [英] How to pass value from a control to another in C# windows form

查看:1344
本文介绍了如何在C#窗体中将值从控件传递到另一个控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我想在usercontrol配置文件中计算datagridview(dtuserpro)的记录数,并将其传递给另一个usercontrol仪表板中的标签,但我没有价值。



我尝试了什么:



Good day everyone, please i am trying to count the number of records of a datagridview(dtuserpro) in a usercontrol profile and pass it to a label in another usercontrol dashboard but i get no value.

What I have tried:

public partial class userprofile : UserControl
{
   private string count1;
   public string Countt
   {
      get { return count1; }
      set { count1 = value; }
   }

   public userprofile()
   {
      InitializeComponent();
   }

   SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\odt\Documents\Loanapp.mdf;Integrated Security=True;Connect Timeout=30");
   DataTable dt = new DataTable();

   private void profile_Load(object sender, EventArgs e)
   {
      int count = ((DataTable)this.dtuserpro.DataSource).Rows.Count;
      lblcount.Text = count.ToString();
      Countt = lblcount.Text;
   }

   private void dashboard_Load(object sender, EventArgs e)
   {
      userprofile up = new userprofile();
      metroLabel1.Text = up.Countt;
   }

推荐答案

控件彼此不了解,也不应该知道。



您的表单应该是控件之间传递数据的内容。您的用户控件应将其所需的数据公开为属性,并公开您的表单可以订阅的事件,以通知属性中的数据发生更改。



当属性值更改时,属性设置可以引发事件。表单会得到通知,并可以选择从属性中获取数据并将数据发送到其他控件。



由表单决定如​​何操作与数据,而不是暴露数据的控件。
Controls do not know about each other, and nor should they.

Your form is what should be passing data between controls. Your user control should expose the data it needs to as a property and also expose an event your form can subscribe to to be notified that the data in the property changed.

When the property value changes, the property setting can raise the event. The form gets notified and can chose to pick up the data from the property and send the data to the other control.

It's up to the form to determine what to do with the data, not the control exposing the data.


这篇关于如何在C#窗体中将值从控件传递到另一个控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆