c# – 标签单击事件
发布时间:2020-12-16 01:56:25 所属栏目:百科 来源:网络整理
导读:我正在尝试为一组动态创建的标签创建一个click事件,如下所示: private void AddLBL_Btn_Click(object sender,EventArgs e) { int ListCount = listBox1.Items.Count; int lbl = 0; foreach (var listBoxItem in listBox1.Items) { Label LB = new Label();
我正在尝试为一组动态创建的标签创建一个click事件,如下所示:
private void AddLBL_Btn_Click(object sender,EventArgs e) { int ListCount = listBox1.Items.Count; int lbl = 0; foreach (var listBoxItem in listBox1.Items) { Label LB = new Label(); LB.Name = "Label" + listBoxItem.ToString(); LB.Location = new Point(257,(51 * lbl) + 25); LB.Size = new Size(500,13); LB.Text = listBoxItem.ToString(); Controls.Add(LB); lbl++; } LB.Click += new EventHandler(PB_Click);// error here } protected void LB_Click(object sender,EventArgs e) { webBrowser1.Navigate("http://www.mysite/" + LB);//Navigate to site on label } 我收到一个错误:“当前上下文中不存在名称’LB’”因为我在循环中创建了LB而且我不够聪明知道如何声明LB所以我可以在循环之外使用它. 另外,我想将标签名称(listBoxItem)传递给click事件,并将它放在WebBrowser调用中的位置.例如:webBrowser1.Navigate(“http://www.mysite/”LB); //导航到标签上的网站 解决方法
您的LB对象超出范围,您需要在循环内移动它. (此外,您显示的处理程序称为LB_Click,但您尝试分配PB_Click;我认为这是一个错字).
foreach (var listBoxItem in listBox1.Items) { Label LB = new Label(); LB.Name = "Label" + listBoxItem.ToString(); LB.Location = new Point(257,(51 * lbl) + 25); LB.Size = new Size(500,13); LB.Text = listBoxItem.ToString(); LB.Click += new EventHandler(LB_Click); //assign click handler Controls.Add(LB); lbl++; } 事件处理程序中的发件人将是单击的标签. protected void LB_Click(object sender,EventArgs e) { //attempt to cast the sender as a label Label lbl = sender as Label; //if the cast was successful (i.e. not null),navigate to the site if(lbl != null) webBrowser1.Navigate("http://www.mysite/" + lbl.Text); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |