在此方法中,将根据 sql 查询显示的结果数自动生成流布局面板的按钮。 然后将新按钮添加到事件处理程序中以实现功能。 我的问题是,我想获取特定于我单击的按钮的信息。 分配给按钮的信息是客户端名称、项目类型,在后台,属性 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();
}
触发事件的按钮在 sender
参数中可用...只需将其投回:
void newButton_Click(object sender, EventArgs e)
{
Button myButton = (Button)sender;
// do whatever you want with myButton, not newButton
...
不要使用 newButton
,它只是对您创建的最后一个按钮的引用。实际上,该变量可能应该在创建这些按钮的任何方法中定义。
您可以使用 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;
}
Click
处理程序内部对newButton
的引用与外部的引用相同。
这也消除了创建newButton_Click
方法的需要 - 这通常有利于封装功能。