用户控制:
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);
}
}
}
该表单从数据库加载记录并在每个用户控件的动态创建的文本框中显示每个 LastName。单击动态用户控件时,如何在表单的文本框中显示附加信息,例如地址?
试图:
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"];
}
}
}
}