检查字段是否为空条目,并将字段背景更改为浅黄色
本文关键字:字段 背景 浅黄色 是否 检查 | 更新日期: 2023-09-27 18:27:42
很棒的网站-对我的C#类很有帮助。
我正试图在C#中编写一个方法,该方法将检查字段中的null条目,并将字段背景更改为LightYellow?
该表单是一个显示表单,用于查看SQL数据库中的记录。
这是我尝试过的,但字段名称的变量没有转换为字段名称。
建议?
// YellowBack Method fills background of key fields that are missing data or are NULL
private void YellowBack()
{
//Bool fieldContents = true;
string fieldVariable;
string[] fieldName = { "activity_TitleTextBox", "act_Title2TextBox", "kid_NotesTextBox", "review_AdultTextBox",
"phoneTextBox", "addressTextBox", "cityTextBox", "websiteTextBox", "weblink_TextTextBox",
"hoursTextBox", "admissionTextBox" };
int count = 0;
//Check each field name
for (int index = 0; index < fieldName.Length; index++)
{
fieldVariable == fieldName.Text;
if (fieldVariable.Trim = "")
{
fieldVariable.BackColor = LightYellow;
}
else
{
fieldVariable.BackColor = Window;
}
}
}
您没有使用索引。你应该使用这样的东西:
fieldVariable = fieldName[i].Text;
我还认为您将无法在fieldVariable
上设置属性BackColor
,因为它是一个字符串。您可能应该使用数据库绑定的对象网格或文本控件,并设置其颜色属性。但我不确定这里是否有足够的信息可以继续。
我认为问题在于您正在循环遍历一个字符串列表,并试图将该字符串放入TextBox控件中。相反,您可能应该循环浏览表单上的所有控件,对于每一个TextBox,查看它的名称是否与列表中的名称匹配。然后可以根据Text属性设置控件的背景颜色。
代码还有其他问题,比如在if
语句中,您正在执行赋值(=
)而不是比较(==
)。
我会这么做:
private void HighlightEmptyFields()
{
// Create a list of all the text box names that we want to examine
var textBoxNames = new List<string>
{
"activity_TitleTextBox", "act_Title2TextBox", "kid_NotesTextBox",
"review_AdultTextBox", "phoneTextBox", "addressTextBox", "cityTextBox",
"websiteTextBox", "weblink_TextTextBox", "hoursTextBox", "admissionTextBox"
};
// Loop through every control on the form
foreach (Control formControl in this.Controls)
{
// Find the groupbox control by name
if (formControl.Name != "groupBox1") continue;
// We found the group box, so loop through every control in it
foreach (Control groupBoxControl in formControl.Controls)
{
// Try to cast the control to a TextBox.
var textBoxControl = groupBoxControl as TextBox;
// If the cast fails, move on to the next one...
if (textBoxControl == null) continue;
// Now we have one a textbox control, so see if the
// textBoxNames array contains the name of this text box.
if (textBoxNames.Contains(textBoxControl.Name,
StringComparer.OrdinalIgnoreCase))
{
// We found a match, so set the backcolor based on Text property
if (textBoxControl.Text.Trim() == "")
{
textBoxControl.BackColor = Color.LightYellow;
}
else
{
textBoxControl.BackColor = Color.White;
}
}
}
// Since we found the control we were looking for, we can stop looking
break;
}
}