在此方法中,根据sql查询显示的结果数量,自动为流布局面板生成按钮。然后将新按钮添加到Eventhandler以获取功能。我的问题是,我想获取特定于我点击的按钮的信息。分配给按钮的信息是clientName,projectType,在后台,包含属性clientNo和projectNo以用于参照完整性。我需要的是单击按钮时分配给该按钮的值。
现在,该方法仅返回创建的最后一个按钮。
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();
}
答案 0 :(得分:1)
sender
参数中提供了触发事件的按钮...只需将其转换回来:
void newButton_Click(object sender, EventArgs e)
{
Button myButton = (Button)sender;
// do whatever you want with myButton, not newButton
...
不要使用newButton
,它只是对您创建的最后一个按钮的引用。实际上,该变量应该在 inside 中定义,无论创建这些按钮的方法是什么。
答案 1 :(得分:1)
您可以使用lambda表达式来捕获lambda之外的任何值。
您的代码如下所示:
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 += (s, 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();
};
}
return newButton.Name;
}
newButton
处理程序中对Click
的引用与外部相同。
这也消除了创建newButton_Click
方法的需要 - 这通常适用于封装功能。