In this method, buttons are automatically generated to the flow layout panel based on how many results show up from the sql query. The new buttons are then added to the Eventhandler for functionality. My problem is, I want to get the information that is specific to the button that I click on. The information being assigned to the buttons are clientName, projectType, and in the background, the properties clientNo and projectNo are included for referential integrity. What I need are the values assigned to that button when I click the button.
Right now, the method is only returning the last button created.
private string AddButton()
{
string sql = "SELECT projectType, clientName, projectNo, Client.clientNo FROM Project, Client WHERE Project.ClientNo = Client.ClientNo;";
newConnection = new ConnectToDatabase(sql);
dataReader = newConnection.NewDataReader();
while (dataReader.Read())
{
newButton = new Button();
newButton.Font = new Font("Georgia", 12);
newButton.Size = new Size(194, 80);
newButton.Name = dataReader.GetValue(3).ToString();
newButton.Text = dataReader.GetValue(1).ToString() + "\n" + dataReader.GetValue(0);
flpDisplayProjects.Controls.Add(newButton);
newButton.Click += new System.EventHandler(newButton_Click);
}
return newButton.Name;
}
void newButton_Click(object sender, EventArgs e)
{
string sql = "SELECT projectType, clientName, projectNo FROM Project, Client WHERE Project.ClientNo = Client.ClientNo AND " +
"clientName = '" + newButton.Name + "';";
newConnection = new ConnectToDatabase(sql);
dataReader = newConnection.NewDataReader();
timeTrackingForm newForm = new timeTrackingForm(dataReader);
newForm.Show();
}
The button that fired the event is available in the sender
parameter... just cast it back:
void newButton_Click(object sender, EventArgs e)
{
Button myButton = (Button)sender;
// do whatever you want with myButton, not newButton
...
Don't use newButton
, which is simply a reference to the last button you created. Actually, that variable should probably be defined inside whatever method is creating those buttons.