c#string if else outside按钮 [英] c# string if else outside button
本文介绍了c#string if else outside按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好我有一个问题如何使用if else外部按钮的字符串,因为我必须使用它很多次和许多复选框,所以如何为表单创建一个字符串,只是在里面使用字符串名称? ?
hello i have a question how to use a string with if else outside button because i have to use it so many times and many checkboxes so how can i make a string for a form and just use a string name inside butoon???
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Form1
{
public partial class main : Form
{
public main()
{
InitializeComponent();
}
string test;
{
if (checkBox1.Checked == true)
{
test = "text 1";
}
else
{
test = "text 2";
}
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(test);
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(test);
}
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show(test);
}
}
}
推荐答案
让我试着解密你的问题。
如果我理解,你有一系列的按钮和复选框。
你想带一个通用的例程,它会根据复选框的状态返回一条消息。
如果是这种情况,您可以创建一个新方法并传递控件名称(复选框)。这样的事情:
Let me try to decrypt your question.
If I understand, you have a series of buttons and checkboxes.
And you want to come with a generic routine which would return you a message based on the state of a checkbox.
If that's the case, you could create a new method and pass the control name (checkbox). Something like this:
private string GetMessage(string checkBoxName)
{
if((CheckBox(this.Controls[checkBoxName])).Checked)
{
return string.Format("{0} is checked", checkBoxName);
}
else
{
return string.Format("{0} is not checked", checkBoxName);
}
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(GetMessage("checkBox2"));
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(GetMessage("checkBox1"));
}
使用房产怎么样?它基本上就是你所拥有的:
What about using a property? It's basically what you have there already:
private string Test
{
get
{
if (checkBox1.Checked)
{
return "text 1";
}
else
{
return "text 2";
}
}
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(Test);
}
这篇关于c#string if else outside按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文