Reputation: 1
I have a method name addDays that takes in the first day the month falls in and how many days the month has. This method adds dynamic labels to a table 7x6 which would represent each day of the month of every week. I also added events to each label so the person can click them. The problem I am having is that I need to be able to read the labels that the person has click. Lets say I run the application populate my calendar and I click on the first of the month, I then want to be able to capture the text of that label which would be 1.
Here is the code of my addDays method.
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);
}
}
}
}
}
This is my eventhandler for the labels click
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
Upvotes: 0
Views: 1593
Reputation: 8623
You need to hook up to some event on the Label
when you create it, so after your line:
newLabel = new Label();
you need to add a handler for the Click
event:
newLabel.Click += new EventHandler(days_Click);
Then, inside your Click
event handler, you can get the Label
from the sender
object:
Label selectedLabel = (Label)sender;
string labelText = selectedLabel.Text;
Upvotes: 3