如何获取最后一次点击面板上对象的名称?诀窍是面板上有一大堆按钮(btn [1] ... btn [200])。如何检查是否单击按钮b [180],b [11]或甚至是面板外部(无按钮)?此外,按钮是通过编码在页面加载时生成的。 谢谢。安娜
编辑: 谢谢!出现的另一个问题(这生成了一个NULL对象引用): 我有一个与buttonHandler()处于同一级别的方法,它被命名为HowManyClicked(),并且它是从buttonHandler()中调用的。在HowManyClicked()里面我想将Button btn1 = Panel2.FindControl(x)识别为Button;其中x是,例如,buttonArray [2,3]。但我总是得到NULL。 按钮数组buttonArray是否在生成它的方法之后无法通过名称识别?
public void buttonHandler(object sender, EventArgs e)
{
Button btn = sender as Button;
//string tt = btn.ToolTip.ToString();
btn.BackColor = Color.Red;
statusL.Text = HowManyClicked().ToString();
}
public int HowManyClicked()
{
int sum=0;
for (int a = 0; a < 10; a++)
for (int b = 0; b < 14; b++)
{
string x = "buttonArray[" + a + ", " + b + "]";
statusL.Text = x;
Button btn1 = Panel2.FindControl(x) as Button;
if (btn1.BackColor == Color.Red) sum += 1;
}
return sum;
}
答案 0 :(得分:6)
如@AVD所述,您可以获取发送发送者对象的回发的按钮,您也可以使用按钮对象的CommandName
和CommandArgument
属性(通常在按钮为时使用它们)在Grid
,DataList
等内部,但如果您需要,可以在此上下文中使用它们:
protected void Page_Init(object sender, EventArgs e)
{
var s = Enumerable.Range(1, 10);
foreach (var item in s)
{
var b = new Button();
b.Text = "My Button " + item.ToString();
b.CommandName = "custom command";
b.CommandArgument = item.ToString();
b.Click += new EventHandler(b_Click);
this.myPanel.Controls.Add(b);
}
}
void b_Click(object sender, EventArgs e)
{
var current = sender as Button;
this.lblMessage2.Text = "Clicked from array buttons: <br/>Command Name: " + current.CommandName + "<br/>Args: " + current.CommandArgument + "<br/>Button Unique ID: " + current.UniqueID + "<br/>Client ID: " + current.ClientID;
}
页:
<asp:Panel runat="server" ID="myPanel">
</asp:Panel>
<asp:Label ID="lblMessage2" runat="server" />
此代码生成如下内容:
作为补充说明,Microsoft建议在PreInit
事件中创建动态控件,或者在Init
事件
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.ViewState["count"] = 0;
}
}
protected void Page_Init(object sender, EventArgs e)
{
var s = Enumerable.Range(1, 10);
foreach (var item in s)
{
var b = new Button();
b.Text = "My Button " + item.ToString();
b.Click += new EventHandler(buttonHandler);
this.myPanel.Controls.Add(b);
}
}
void buttonHandler(object sender, EventArgs e)
{
// update here your control
var b = sender as Button;
b.BackColor = Color.Red;
HowManyClicked();
}
private void HowManyClicked()
{
var c = (int)this.ViewState["count"];
c++;
this.ViewState["count"] = c;
this.lblMessage2.Text = "Clicked controls: " + this.ViewState["count"].ToString();
}
这产生了:
答案 1 :(得分:2)
如何获取最后一次点击面板上对象的名称?
click处理程序的第一个参数返回控件/对象的引用已引发事件。
public void buttonHandler(object sender, EventArgs e)
{
Button btn=sender as Button;
....
}
答案 2 :(得分:0)
我刚刚通过重新定义HowManyClicked()找到了另一个解决方案,所以我在下面添加它。不确定为什么第一种方法(我的问题中的方法)也不起作用。这是:
public int HowManyClicked()
{
int sum=0;
foreach (Control cnt in this.Panel2.Controls)
if (cnt is Button)
{
Button btn = (Button)cnt;
if (btn.BackColor == Color.Red)
sum += 1;
}
return sum;
}
}
谢谢大家!