我想解锁表单上的多数文本框,但不是所有文本框。目前我正在使用这种解锁所有文本框的方法:
private void UnlockVnos(Control control)
{
foreach (Control c in control.Controls)
{
if (c is TextBox)
{
((TextBox)c).ReadOnly = false;
((TextBox)c).BackColor = Color.FromArgb(255, 255, 192);
}
}
}
我的问题是:如何排除我不想解锁的特定文本框(我必须遍历大约50个文本框并解锁所有文本框,除了其中一些必须保持锁定。我想到的第一件事就是设置文本框'Tag'属性,但不知怎的,我不能让它在我的方法中工作。任何帮助都赞赏。
答案 0 :(得分:3)
为此,我将我不想解锁的方框的文本框标签设置为" DoNotUnlock"。
foreach (Control c in this.Controls)
{
if (c is TextBox && (string)c.Tag != "DoNotUnlock")
{
((TextBox)c).ReadOnly = false;
((TextBox)c).BackColor = Color.FromArgb(255, 255, 192);
}
}
使用密钥字典。我想要更多功能的词典,Bool可以与键结合使用。不久将添加一个代码示例。
private void UnlockVnos()
{
Dictionary<string, bool> mytags = new Dictionary<string, bool>();
mytags.Add("DoNotUnlock", false);
mytags.Add("StayAwayFromThisBox", false);
mytags.Add("DontEvenDateUnlockThis", false);
foreach (Control c in this.Controls)
{
if ((c is TextBox && c.Tag == null || !mytags.Keys.Contains((string)c.Tag)))
{
((TextBox)c).ReadOnly = false;
((TextBox)c).BackColor = Color.FromArgb(255, 255, 192);
}
}
}
在字典中使用bool的第3个样本
private void UnlockVnosAgains()
{
//here we have a Dictionary of all the tags you want to handle.
//True for boxes which should be readonly, false for boxes which should not be.
Dictionary<string, bool> mytags = new Dictionary<string, bool>();
mytags.Add("SomeTag1", false);//leave it alone
mytags.Add("SomeTag2", true);//make it readonly
mytags.Add("SomeTag3", true);//make it readonly
mytags.Add("SomeTag4", false);//leave it alone
mytags.Add("DoNotUnlock", true);//make it readonly
foreach (Control c in this.Controls)
{
//if C is a textbox, and the Tag is NOT null and the dictionary contains the tag
if ((c is TextBox && c.Tag != null && mytags.Keys.Contains((string)c.Tag)))
{
((TextBox)c).ReadOnly = mytags[(string)c.Tag];//assign the appropriate bool from the dictionary
((TextBox)c).BackColor = Color.FromArgb(255, 255, 192);//do your color thing... wink wink, this one could be stored along with your true or false too
}
}
}
答案 1 :(得分:2)
我假设您对所有不想解锁的文本框都有相同的标记值。
请尝试以下操作:
private void UnlockVnos(Control control)
{
foreach (Control c in control.Controls)
{
if (c is TextBox)
{
var tBox = (TextBox)c;
var tag = Convert.ToString(tBox.Tag);
if (tag !="YourTagValue")){ //Take care of case-sensitivity
tBox.ReadOnly = false;
tBox.BackColor = Color.FromArgb(255, 255, 192);
}
}
}
}
答案 2 :(得分:0)
private void UnlockVnos(Control control)
{
foreach (Control c in control.Controls)
{
if (c is TextBox)
{
var textbox = (TextBox)c;
textbox.ReadOnly = textbox.Tag == "myTag";
textbox.BackColor = Color.FromArgb(255, 255, 192);
}
}
}