实例:
/// <summary>
/// 用户信息结构
/// </summary>
public struct TUSER
{
public string LoginName;
public string LoginPass;
public string TrueName;
public string EMail;
public int Level;
}
/// <summary>
/// 获得所有注册用户
/// </summary>
/// <param name="USERINFO">返回用户信息结构</param>
public bool GetUsers(out TUSER[] G_USERINFO)
{
USEROP.TUSER[] f_TUSER;
int CurRec = 0; //初始化记录计数器
int rec_count =0; //计算总记录数
SqlConnection myConn = new SqlConnection(connectionString);
string cmd="select * from " +m_Table; //SQL查询语句
SqlCommand mycmd=new SqlCommand(cmd,myConn);
mycmd.Connection.Open(); //打开连接
SqlDataReader adr = null; //创建数据读取器
try
{
adr = mycmd.ExecuteReader();
while(adr.Read ())
{
rec_count += 1;
}
myConn.Close(); //关闭数据库连接
mycmd.Connection.Open (); //打开数据库连接
try
{
adr = mycmd.ExecuteReader ();
f_TUSER = new USEROP.TUSER[rec_count];
while(adr.Read())
{
f_TUSER[CurRec].LoginName = adr["US_LOGINNAME"].ToString();
f_TUSER[CurRec].LoginPass = adr["US_LOGINPASS"].ToString ();
f_TUSER[CurRec].TrueName = adr["US_TrueName"].ToString ();
f_TUSER[CurRec].EMail = adr["US_EMail"].ToString ();
f_TUSER[CurRec].Level = Int32.Parse (adr["US_Level"].ToString ());
CurRec += 1;
}
G_USERINFO = f_TUSER;
myConn.Close (); ///关闭连接
return true;
}
catch
{
myConn.Close();
f_TUSER = new USEROP.TUSER[1];
f_TUSER[0].LoginName = "";
f_TUSER[0].LoginPass = "";
f_TUSER[0].TrueName = "";
f_TUSER[0].EMail = "";
f_TUSER[0].Level = 0;
G_USERINFO = f_TUSER;
return false;
}
}
catch
{
myConn.Close ();
f_TUSER = new USEROP.TUSER[1];
f_TUSER[0].LoginName = "";
f_TUSER[0].LoginPass = "";
f_TUSER[0].TrueName = "";
f_TUSER[0].EMail = "";
f_TUSER[0].Level = 0;
G_USERINFO = f_TUSER;
return false;
}
/ 在WEB FORM中调用如下:
private void Button3_Click(object sender, System.EventArgs e)
{
KSBM.USEROP.TUSER[] f_TUSER; // = new KSBM.USEROP.TUSER(); ///为什么不"new" 一个结构数组呢?因为传进来的已是我们要的数据了,所以只要开辟一个存储空间就行了.
KSBM.USEROP f_USOP = new KSBM.USEROP();
bool ret=f_USOP.GetUsers (out f_TUSER); ///调用函数,取得结构数组及信息
if(f_TUSER.Length !=0) //数据长度为0时,表明无返回数据.
{
for(int iloop=0;iloop<f_TUSER.Length;iloop++) ///遍历数组并输出到客户端的浏览器
{
Response.Write (f_TUSER[iloop].LoginName);
Response.Write (f_TUSER[iloop].LoginPass);
Response.Write (f_TUSER[iloop].TrueName);
Response.Write (f_TUSER[iloop].EMail);
Response.Write (f_TUSER[iloop].Level);
}
}