ontrol1.intLoginTime +"\ne''s strUserID="+e.strUserID,"Test",MessageBoxButtons.OK);
}
此时运行客户
程序可得以下结果:
This is in test form!
this is the process in DB
this is the btnOK_click function!
结果表明单击btnOK按钮时执行组件中的OnSubmitLogin(new EventLoginArgs(txtID.Text,txtName.Text,txtPWD.Text)),此方法又调用 SubmitLogin(this,e),从而激发SubmitLogin事件,userControl1_SubmitLogin就进行响应,故打印第一行。
跟着是执行TestUserInDB,它打印出第二行。
最后是返回到btnOK_Click中输出最后一行。
注意若btnOK_Click中的OnSubmitLogin和TestUserInDB所在的行调换位置,其结果是不同的.第二个例子中,二者的位置调换,先进行数据库
查询判断,再在SubmitLogin的事件响应userControl1_SubmitLogin中处理结果,下面的是例子二的主要代码:
public delegate void UserLoginEventHandler(object sender,EventLoginArgs e);
public delegate void CancelEventHandler(object sender,EventArgs e);
public event UserLoginEventHandler SubmitLogin;
public event CancelEventHandler Cancel;
protected virtual void OnSubmitLogin(EventLoginArgs e)
{
if(this.SubmitLogin!=null)
{
SubmitLogin(this,e);
}
}
protected virtual void OnCancel(EventArgs e)
{
if(this.Cancel!=null)
Cancel(this,e);
}
public string Server
{
}
public string DataBase
{
}
public string TableSet
{
}
public string UserForDB
{
}
public string PWDForDB
{
}
public bool TestUserInDB(EventLoginArgs e)
{
//MessageBox.Show("this is the process for DB!","TestUserInDB",MessageBoxButtons.OK);
bool bOK = false;
if(this.strDataBase!=null && this.strServer!=null && this.strUserForDB!=null)
{
if(this.strPWDForDB==null)
this.strPWDForDB = "";
string strConnection = "server="+this.strServer +";database="+this.strDataBase
+";UID="+this.strUserForDB +";PWD="+this.strPWDForDB;
string strSQL = "select UserID,UserName,UserPWD from "+this.strTableSet+" where
UserID=''"+e.strUserID+"'' and UserName=''"+e.strUserName +"'' and UserPWD=''"+e.strUserPWD+"''";
SqlConnection conn = new SqlConnection(strConnection);
try
{
conn.Open();
}
catch(SqlException ex)
{
MessageBox.Show("数据库不能打开!请检查有关参数.","Error",MessageBoxButtons.OK);
return false;
}
SqlDataAdapter da = new SqlDataAdapter(strSQL,conn);
DataSet ds = new DataSet();
try
{
da.Fill(ds,this.strTableSet);
}
catch(SqlException ex)
{
}
foreach(DataRow row in ds.Tables[this.strTableSet].Rows)
{
if(row != null)
{
bOK = true;
}
}
.
}
else
{
bOK = false;
}
return bOK;
}
private void btnOK_Click(object sender, System.EventArgs e)
{
if(txtID.Text != ""&&txtName.Text !=""&&txtPWD.Text !="")
{
intLoginTime++;
bLogin = TestUserInDB(new EventLoginArgs(txtID.Text,txtName.Text,txtPWD.Text));
if(!bLogin)
MessageBox.Show("Login in Failed!","Login Error",MessageBoxButtons.OK);
else
OnSubmitLogin(new EventLoginArgs(txtID.Text,txtName.Text,txtPWD.Text));
}
else
{
MessageBox.Show("Your must input all the items!","Logi