动态用户控制点击事件
用户控件:
private string lastName; public string LastName { get { return lastName; } set { lastName = value; lastNameTextBox.Text = value; } }
形成:
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString)) { myDatabaseConnection.Open(); using (SqlCommand SqlCommand = new SqlCommand("Select LasatName from Employee", myDatabaseConnection)) { int i = 0; SqlDataReader DR1 = SqlCommand.ExecuteReader(); while (DR1.Read()) { i++; UserControl2 usercontrol = new UserControl2(); usercontrol.Tag = i; usercontrol.LastName = (string)DR1["LastName"]; usercontrol.Click += new EventHandler(usercontrol_Click); flowLayoutPanel1.Controls.Add(usercontrol); } } }
表单从数据库加载记录并显示动态创建的每个usercontrols文本框中的每个LastName。 如何在单击dynamic-usercontrol时显示表单文本框中的地址等附加信息?
尝试:
private void usercontrol_Click(object sender, EventArgs e) { using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString)) { myDatabaseConnection.Open(); using (SqlCommand mySqlCommand = new SqlCommand("Select Address from Employee where LastName = @LastName ", myDatabaseConnection)) { UserControl2 usercontrol = new UserControl2(); mySqlCommand.Parameters.AddWithValue("@LastName", usercontrol.LastName; SqlDataReader sqlreader = mySqlCommand.ExecuteReader(); if (sqlreader.Read()) { textBox1.Text = (string)sqlreader["Address"]; } } } }
第一。 在您的第一个代码片段中,您执行“从…中选择ID”,但期望在阅读器中找到字段“LastName” – 无法正常工作。
第二。 如果您知道需要Employee
表中的更多信息,我建议您将它存储在放置LastName
的同一UserControl
中。 执行“Select * from …”,将另一个字段和属性添加到UserControl2
并在Read
循环中分配它:
usercontrol.Address = (string)DR1["Address"];
第三。 在您的第二个代码片段中,使用
UserControl2 usercontrol = (UserControl2)sender;
代替
UserControl2 usercontrol = new UserControl2();
因为新创建的用户控件不会分配任何LastName
。
然后:
private void usercontrol_Click(object sender, EventArgs e) { UserControl2 usercontrol = (UserControl2)sender; textBox1.Text = usercontrol.Address; }
在用户控件UserControl2中 (在构造函数或InitializeComponent方法中),您应该将click事件转发给潜在的侦听器。
像这样的东西:
上述就是C#学习教程:动态用户控制点击事件分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
public UserControl2() { ... this.lastNameTextBox.Click += (s, a) => OnClick(a); ... }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1027878.html