UserControl:
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);
}
}
}
窗体从数据库加载记录,并在动态创建的每个用户控件文本框中显示每个姓氏。单击动态用户控件时,如何在表单的文本框中显示附加信息,例如地址?
尝试:
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
中。执行"从...中选择*",添加另一个字段和属性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 方法中(,应将单击事件转发给潜在的侦听器。
像这样:
public UserControl2()
{
...
this.lastNameTextBox.Click += (s, a) => OnClick(a);
...
}