UserControl:
private string lastName;
public string LastName
{
get { return lastName; }
set
{
lastName = value;
lastNameTextBox.Text = value;
}
}
Form:
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);
}
}
}
The form loads the records from database and display each LastName in each usercontrols' textbox that created dynamically. How to show additonal information such as address in form's textbox when a dynamic-usercontrol is click?
Attempt:
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"];
}
}
}
}
Inside your user control UserControl2 (in the constructor or InitializeComponent method) you should forward the click event to the potential listeners.
Something like that:
First. In your first code fragment, you execute "Select ID from ...", but expect to find field "LastName" in the reader - not going to work.
Second. If you know that you will need more information from
Employee
table, I suggest that you store it in the sameUserControl
where you put theLastName
. Execute "Select * from ...", add another field and property toUserControl2
and assign it in theRead
loop:Third. In your second code fragment, use
instead of
because newly created user control will not have any
LastName
assigned.Then: