在aspx页面 function check() { if (document.Form1.userid2.value =="") { alert("用户帐号不能为空!"); document.Form1.userid2.focus (); return false; } if (document.Form1.paswd1.value =="") { alert("密码不能为空!"); document.Form1.paswd1.focus (); return false; } } 在.cs页面 this.ImageButton5.Attributes.Add ("onclick","return check();");
这个好说,用一个循环就可以了: foreach (Control con in this.Controls) { TextBox _tb = con as TextBox; if (_tb != null && _tb.Text.Trim()==string.Empty) { _tb.Focus(); break; } }
foreach( Control c in this.Controls ) { if( c is TextBox ) //your work }
{
textBox1.Focus();
return ;
}
用控件的Focus()
这个方法对于控件数量比较少的时候是很好用的,但是我如果有10几个textbox,那我不是要每个都if一遍???
有没有一种办法可以自动查询到是哪个控件???
function check()
{
if (document.Form1.userid2.value =="")
{
alert("用户帐号不能为空!");
document.Form1.userid2.focus ();
return false;
}
if (document.Form1.paswd1.value =="")
{
alert("密码不能为空!");
document.Form1.paswd1.focus ();
return false;
}
}
在.cs页面
this.ImageButton5.Attributes.Add ("onclick","return check();");
foreach (Control con in this.Controls)
{
TextBox _tb = con as TextBox;
if (_tb != null && _tb.Text.Trim()==string.Empty)
{
_tb.Focus();
break;
}
}
{
if( c is TextBox )
//your work
}
{
if(ct.GetType() == typeof(System.Windows.Forms.TextBox))
{
if(ct.Text.Trim().Length ==0)
{
ct.Focus();
return;
}
}
}
foreach(System.Windows.Forms.Control ct in this.Controls)这个this这里指的是容纳textbox的容器,你的“对象引用设置到对象的实例”应该是这个ct为被定义~~~
{
if(ct.GetType() == typeof(System.Windows.Forms.TextBox))
{
if(ct.Text.Trim().Length ==0)
{
ct.Focus();
return;
}
}
}
{
ComboBox Cb = Ctrl as ComboBox;
if (Cb.SelectedText == null)
{
Cb.Focus();
break;
}
}还是上面那个错我现在有3个ComboBox,都放在同一个GroupBox里面!!!
{
foreach (Control tmp in this.Controls)
{
TextBox textbox = tmp is TextBox ? (TextBox)tmp : null;
if (textbox != null & tmp.Text == "") tmp.Focus();
}
}
给分!
是不是只有一个Button和三个TextBox呢?
{
foreach (Control tmp in this.groupBox1.Controls)
{
if (tmp is ComboBox)
{
ComboBox cb = (ComboBox)tmp;
if (cb.Text.Trim() == string.Empty)
{
cb.Focus();
break;
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
//获得被点击的Button
Button btn1 = sender as Button;
//如果转换没有成功,就退出
if(btn1 == null)
{
return;
}
//因为你说你的Button和Combox控件放在同一个容器中
//所以我们获得Button的父容器,然后遍历父容器中的控件
foreach (Control ctrl in btn1.Parent.Controls)
{
//在这里声明可以避免多次声明
//使用as转换,可以保证不抛出异常
ComboBox cb = ctrl as ComboBox;
//如果转换没有成功,就继续
if(cb == null)
{
continue;
}
//使用Length判断可以提高效率。
//本质上cb.Text.Trim() == String.Empty最终判断的还是两个字符串长度是否相等。
if (cb.Text.Trim().Length == 0)
{
cb.Focus();
//只设定第一个找到的长度为0的ComboBox控件的焦点
break;
}
}
}