[英]c# how to unlock multiple text boxes
我想解鎖大多數表單,但不是所有文本框。 目前,我正在使用這種方法來解鎖所有文本框:
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個文本框並對其全部進行解鎖,除了其中約10個必須保持鎖定狀態。)我想到的是設置文本框的'Tag'屬性,但是以某種方式我無法使其在我的方法中起作用。
為此,我將不想解鎖的框的文本框標簽設置為“ 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);
}
}
}
在字典中使用布爾值的第三個樣本
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
}
}
}
我假設您不想解鎖的所有文本框都具有相同的標記值。
請嘗試以下操作:
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);
}
}
}
}
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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.