我有一个方法名称addDays,它接收月份的第一天和月份的天数。此方法将动态标签添加到表7x6,表7x6表示每周的每个月的每一天。我还为每个标签添加了事件,以便用户可以单击它们。我遇到的问题是我需要能够阅读该人点击的标签。假设我运行应用程序填充我的日历,然后点击本月的第一天,然后我希望能够捕获该标签的文本,即1。 这是我的addDays方法的代码。
private void addDays(int day,int totaldays)
{
int reset = 0;
Label newlabel;
string label;
int labelnum;
Console.WriteLine("testoutputbeforebig forloop");
//DayTableHold.Controls.Add(newlabel, 0, 6);
int numday = 0;
for (int coll = 0; coll <= 7; coll++)
{
for (int row = 0; row <=6; row++)
{
if (numday < totaldays)
{
newlabel = new Label();
newlabel.AutoSize = true;
if (row==day &&coll==0)
{
labelnum = numday + 1;
label = labelnum.ToString();
newlabel.Text = label;
newlabel.Margin = new System.Windows.Forms.Padding(17, 0, 10, 0);
newlabel.Click += new System.EventHandler(days_Click);
DayTableHold.Controls.Add(newlabel, row, coll);
numday++;
reset = 1;
if (row == 6)
{
coll = 1;
}
else coll = 0;
Console.WriteLine("testoutput1 " + numday + " " + label);
}
else if (reset == 1)
{
labelnum = numday + 1;
label = labelnum.ToString();
newlabel.Text = label;
newlabel.Margin = new System.Windows.Forms.Padding(17, 0, 10, 0);
newlabel.Click += new System.EventHandler(days_Click);
DayTableHold.Controls.Add(newlabel, row, coll);
numday++;
Console.WriteLine("test output2 " + numday + " " + label);
}
}
}
}
}
这是我点击标签的事件处理程序
private void days_Click(object sender, EventArgs e)
{
//here is were i want to capture the labels of the clicks.
count++;
Console.WriteLine("day was click"+ count);
} enter code here
答案 0 :(得分:3)
您需要在创建Label
时与某个事件挂钩,所以在您的行之后:
newLabel = new Label();
您需要为Click
事件添加处理程序:
newLabel.Click += new EventHandler(days_Click);
然后,在Click
事件处理程序中,您可以从Label
对象获取sender
:
Label selectedLabel = (Label)sender;
string labelText = selectedLabel.Text;