[英]C# change label text when button clicked multiple times
Sorry I am new to this just wondering if someone can help, I am trying to get my label to change its text every time I click the button. 抱歉,我对此很陌生,只是想知道是否有人可以提供帮助,因此我试图让我的标签每次单击按钮时都更改其文本。 Not sure how I should go about it. 不知道我应该怎么做。 Can anyone help me please. 谁能帮我。
private void button1_Click(object sender, EventArgs e)
{
string[] MonthName;
MonthName = new string[12];
MonthName[0] = "January";
MonthName[1] = "February";
MonthName[2] = "March";
MonthName[3] = "April";
MonthName[4] = "May";
MonthName[5] = "June";
MonthName[6] = "July";
MonthName[7] = "August";
MonthName[8] = "September";
MonthName[9] = "October";
MonthName[10] = "November";
MonthName[11] = "December";
label1.Text = (MonthName[0]);
label1.Text = (MonthName[1]);
Might be easier to do it this way: 这样做可能会更容易:
DateTime currentDate = new DateTime(DateTime.Now.Year, 1, 1); // Per Habib's suggestion
private void button1_Click(object sender, EventArgs e) {
label1.Text = currentDate.ToString("MMMM");
currentDate = currentDate.AddMonths(1);
}
This should do the trick: 这应该可以解决问题:
Declare the array and an int in the class 在类中声明数组和一个int
string[] MonthName = { "Jan", "Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" };
static int i = 0;
Then in the button click 然后在按钮中单击
protected void btnAddMonth_Click(object sender, EventArgs e)
{
lblMonth.Text = MonthName[i];
i = (i+1) % 12;
}
Something like the below code. 类似于以下代码。 Please mind that this is not the most elegant code, but I wanted to keep it simple as you said you are new to this. 请注意,这不是最优雅的代码,但是我想保持它的简单性,因为您说自己是新手。
var Months = new List<string>
{
"January",
"February",
"March",
"April",
"May",
"July",
"August",
"September",
"October",
"November",
"December"
};
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(labelHiddenCounter.Text))
labelHiddenCounter.Text = "0";
if(labelHiddenCounter.Text == "11")
labelHiddenCounter.Text = "-1";
var nextCounter = Convert.ToInt32(labelHiddenCounter.Text) + 1;
label1.Text = (Months[nextCounter]);
labelHiddenCounter.Text = nextCounter.ToString();
}
If you want random months to appear whenever you click the button use. 如果您希望每当您单击按钮时显示随机的月份,请使用。
var random = new Random();
var months = new List<string>
{
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
};
int index = random.Next(months.Count);
label1.Text = (months[index]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.