每做完一个项目,就可以有很多的经验跟技巧学到,感谢公司能给我这么一个机会做这么一个大项目,让我从一个从刚学会一点ASP.Net的菜鸟过渡到可以用 c#正常手写相关常用模块的一个真正的程序员,一个人做项目可以学得很多很多的东西,当然其中碰到困难也只能靠自己一个人去解决.为了让大家更好的学习, 我把常用的模块写成一个个方法,希望能对大家有用.每个人都有不同的算法跟代码习惯,而且个人水平有限,欢迎大家多多指正.
前提准备:
由于项目是采用SQL数据库,所以我们先在web.config中设置好数据库连接
<appSettings>
<add key="Conn" value="Server=(local);Database=dezai;User ID=sa;"></add>
</appSettings>
之后在CS代码中要注意引用
c#
using System.Data.Sqlclient;
using System.Data;
using System.Configuration;
vb.net
Imports System.Data.Sqlclient
Imports System.Data
Imports System.Configuration
以下就是常用的模块
1.会员登陆模块
用户控件:
TextBox:TxtUser 用户名 TxtPwd 密码
Label:LblError 错误提示
存储过程:user_login
[code]
CREATE procedure user_login
@user_name varchar(50),
@user_password varchar(50)
as
select * from userwhere [User_Name] = @User_Name and [User_Pwd] = @User_Password
if @@rowcount>0
begin
update [users] set user_LoginTimes=user_LoginTimes+1 where [User_Name] = @User_Name and [User_Pwd] = @User_Password
end
GO
[/code]
C#.Net
[code]
Private void memberlogin()
{
SqlConnection conndb=new SqlConnection(ConfigurationSettings.AppSettings["Conn"]);
conndb.Open();
SqlCommand cmdlogin = new SqlCommand("User_login",conndb);
cmdlogin.CommandType = CommandType.StoredProcedure;
cmdlogin.Parameters.Add("@user_name",TxtUser.Text.Trim());
cmdlogin.Parameters.Add("@user_password",TxtPwd.Text.Trim());
SqlDataReader reader=cmdlogin.ExecuteReader();
if(reader.Read())
{
Session["user"]=reader["user_id"].ToString();
Session["com"]=reader["com_id"].ToString();
string url;
url="../user/index.aspx?userid="+ Session["userid"] +"&comid="+ Session["comid"] +"";
Response.Redirect(url);
}
else
{
LblError.Text ="Invalid Username or password!Please try again!";
}
}
[/code]
[color=Red]VB.Net[/color]
[code]
Private Sub memberlogin()
Dim conndb As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("Conn"))
conndb.Open()
Dim cmdlogin As SqlCommand = New SqlCommand("User_login",conndb)
cmdlogin.CommandType = CommandType.StoredProcedure
cmdlogin.Parameters.Add("@user_name",TxtUser.Text.Trim())
cmdlogin.Parameters.Add("@user_password",TxtPwd.Text.Trim())
Dim reader As SqlDataReader = cmdlogin.ExecuteReader()
If reader.Read() Then
Session("user")=reader("user_id").ToString()
Session("com")=reader("com_id").ToString()
Dim url As String
url="../user/index.aspx?userid="+ Session("userid") +"&comid="+ Session("comid") +""
Response.Redirect(url)
Else
LblError.Text ="Invalid Username or password!Please try again!"
End If
End Sub
[/code]
2.验证注册用户是否存在
用户控件:
TextBox: TxtMemberID
Label: LblChk
c#代码:
[code]
private bool idcheck()
{
SqlConnection conndb= new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
conndb.Open();
string memberid=TxtMemberId.Text.Trim();
string sql="select User from users where User_Name ='"+memberid+"'";
SqlCommand strchk=new SqlCommand(sql,conndb);
SqlDataReader reader=strchk.ExecuteReader();
if(reader.Read())
{
LblChk.Text="Sorry! this memberid was registed,Please choose another!";
Response.Write("<script>alert(\"Invalid member id\");</script>");
Response.End();
return false;
}
else
{
return true;
}
[/code]
[color=Black]VB.Net 代码[/color]
[code]
private Boolean idcheck()
{
Dim conndb As SqlConnection = New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("conn"))
conndb.Open()
Dim memberid As String = TxtMemberId.Text.Trim()
Dim sql As String = "select User from users where User_Name ='"+memberid+"'"
Dim strchk As SqlCommand = New SqlCommand(sql,conndb)
Dim reader As SqlDataReader = strchk.ExecuteReader()
If reader.Read() Then
LblChk.Text="Sorry! this memberid was registed,Please choose another!"
Response.Write("<script>alert(\"Invalid member id\");</script>")
Response.End()
Return False
Else
Return True
End If
[/code]
3.新用户注册
用户控件:
TextBox:TxtMemberId TxtPwd TxtEmail
ListBox:LstIndustry
存储过程:Users_Insert
[code]
/*
作者:dezai
用途:新进会员的增加注册,同时注册与其相关的企业名录
日期:2006-3-1
*/
CREATE PROCEDURE Users_Insert
@User_Id int output,
@User_Type bit,
@User_Name char(100),
@User_Pwd char(100),
@User_Email char(100)
AS
begin tran
INSERT INTO [Users]
(
[user_type],
[user_name],
[user_pwd],
[user_Email]
)
values
(
@User_Type,
@User_Name,
@User_Pwd,
@User_Email
)
if @@error<>0 goto error
set @user_Id=@@identity
Commit tran
return
ERROR:
set @User_Id = 0
rollback tran
GO
[/code]
c#代码:
[code]
private void reguser()
{
SqlConnection conndb=new SqlConnection(ConfigurationSettings.AppSettings["Conn"]);
SqlCommand cmdinsert = new SqlCommand("Users_Insert",conndb);
cmdinsert.CommandType=CommandType.StoredProcedure;
int intAuthorCount;
cmdinsert.Parameters.Add("@User_Name",TxtMemberId.Text.ToString());
cmdinsert.Parameters.Add("@User_Pwd",TxtPwd.Text.ToString());
cmdinsert.Parameters.Add("@User_Email",TxtEmail.Text.ToString());
cmdinsert.Parameters.Add("@User_Industry",LstIndustry.SelectedValue);
SqlParameter parmReturnValue = new SqlParameter("@User_id", SqlDbType.Int);
parmReturnValue.Direction = ParameterDirection.Output;
cmdinsert.Parameters.Add(parmReturnValue);
conndb.Open();
cmdinsert.ExecuteNonQuery();
intAuthorCount = (int)cmdinsert.Parameters[ "@user_id"].Value;
conndb.Close();
}
[/code]
[color=Red]VB.Net代码[/color]
[code]
Private Sub reguser()
Dim conndb As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("Conn"))
Dim cmdinsert As SqlCommand = New SqlCommand("Users_Insert",conndb)
cmdinsert.CommandType=CommandType.StoredProcedure
Dim intAuthorCount As Integer
cmdinsert.Parameters.Add("@User_Name",TxtMemberId.Text.ToString())
cmdinsert.Parameters.Add("@User_Pwd",TxtPwd.Text.ToString())
cmdinsert.Parameters.Add("@User_Email",TxtEmail.Text.ToString())
cmdinsert.Parameters.Add("@User_Industry",LstIndusTry.SelectedValue)
Dim parmReturnValue As SqlParameter = New SqlParameter("@User_id",SqlDbType.Int)
parmReturnValue.Direction = ParameterDirection.Output
cmdinsert.Parameters.Add(parmReturnValue)
conndb.Open()
cmdinsert.ExecuteNonQuery()
intAuthorCount = CType(cmdinsert.Parameters( "@user_id").Value, Integer)
conndb.Close()
End Sub
[/code]
4.图片上传
c#.Net
[code]private void uppic()
{
string mPath;
string imagePath;
string imageType;
string imageName;
DateTime dtmDate;
dtmDate = DateTime.Now;
if(""!=this.fileup.PostedFile.FileName)
{
imagePath = this.fileup.PostedFile.FileName;
imageType = imagePath.Substring(imagePath.LastIndexOf(".")+1);
imageName=imagePath.Substring(imagePath.LastIndexOf("\\")+1);
if("jpg" != imageType && "gif" !=imageType && "png" !=imageType && "PNG" !=imageType && "GIF" !=imageType && "JPG" !=imageType)
{
Response.Write("<script language='javascript'>alert('sorry!Please choose *.jpg or *.gif or *.png');</script>");
return;
}
else
{
try
{
mPath=Server.MapPath("upfile");
this.fileup.PostedFile.SaveAs(mPath+"\\"+"dezaistudio"+dtmDate.ToString("yyyyMMddhhmmss")+imageName);
this.ImageSmall.ImageUrl = "dezaistudio"+dtmDate.ToString("yyyyMMddhhmmss")+imageName;
Response.Write("<script language='javascript'>alert('upload succesful');</script>");
TxtPicPath.Text = this.ImageSmall.ImageUrl.ToString().Trim();
}
catch
{
Response.Write("error");
}
}
}
}
[/code]
[color=Red]VB.Net代码[/color]
[code]
Private Sub uppic()
Dim mPath As String
Dim imagePath As String
Dim imageType As String
Dim imageName As String
Dim dtmDate As DateTime
dtmDate = DateTime.Now
If ""<>Me.fileup.PostedFile.FileName Then
imagePath = Me.fileup.PostedFile.FileName
imageType = imagePath.Substring(imagePath.LastIndexOf(".")+1)
imageName=imagePath.Substring(imagePath.LastIndexOf("\\")+1)
If "jpg" <> imageType And "gif" <>imageType And "png" <>imageType And "PNG" <>imageType And "GIF" <>imageType And "JPG" <>imageType Then
Response.Write("<script language='javascript'>alert('sorry!Please choose *.jpg or *.gif or *.png');</script>")
Return
Else
Try
mPath=Server.MapPath("upfile")
Me.fileup.PostedFile.SaveAs(mPath+"\\"+"dezaistudio"+dtmDate.ToString("yyyyMMddhhmmss")+imageName)
Me.ImageSmall.ImageUrl = "dezaistudio"+dtmDate.ToString("yyyyMMddhhmmss")+imageName
Response.Write("<script language='javascript'>alert('upload succesful');</script>")
TxtPicPath.Text = Me.ImageSmall.ImageUrl.ToString().Trim()
Catch
Response.Write("error")
End Try
End If
End If
End Sub
[/code]
5.DataList分页(其实Repeart也可采用这个,只是改一下控件名而已)
用户控件
DataList: DlstInfolist
Label:lblCurrentPage
HyperLink:lnkNext LnkPrev
存储过程:supplyinfo_select
[code]
/*
查询大类下所有的supplyinfo
2006-4-10
*/
create procedure supplyinfo_select
@bigclassid int
as
select * from supply
where
Supply_CatID=@bigclassid
GO
[/code]
c#.Net
[code]
private void dlstsupplyinfolist()
{
SqlConnection conndb = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
conndb.Open();
string bigid=Request.QueryString["bigid"].Trim();
SqlDataAdapter strbuyinfo = new SqlDataAdapter("supplyinfo_select",conndb);
strbuyinfo.SelectCommand.CommandType = CommandType.StoredProcedure;
strbuyinfo.SelectCommand.Parameters.Add("@bigclassid",bigid);
DataSet ds = new DataSet();
strbuyinfo.Fill(ds);
{
PagedDataSource objPds = new PagedDataSource();
objPds.DataSource = ds.Tables[0].DefaultView;
objPds.AllowPaging = true;
objPds.PageSize = 5;
int CurPage;
if (Request.QueryString["Page"] != null)
CurPage=Convert.ToInt32(Request.QueryString["Page"]);
else
CurPage=1;
objPds.CurrentPageIndex = CurPage-1;
lblCurrentPage.Text = "Page: " + CurPage.ToString();
if (!objPds.IsFirstPage)
lnkPrev.NavigateUrl=Request.CurrentExecutionFilePath + "?id=" + bigid +"&Page=" + Convert.ToString(CurPage-1);
if (!objPds.IsLastPage)
lnkNext.NavigateUrl=Request.CurrentExecutionFilePath + "?id=" + bigid +"&Page="+ Convert.ToString(CurPage+1);
DlstInfolist.DataSource=objPds;
DlstInfolist.DataKeyField="Supply";
DlstInfolist.DataBind();
}
}
[/code]
VB.Net
[code]
Private Sub dlstsupplyinfolist()
Dim conndb As SqlConnection = New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("conn"))
conndb.Open()
Dim bigid As String = Request.QueryString("bigid").Trim()
Dim strbuyinfo As SqlDataAdapter = New SqlDataAdapter("supplyinfo_select",conndb)
strbuyinfo.SelectCommand.CommandType = CommandType.StoredProcedure
strbuyinfo.SelectCommand.Parameters.Add("@bigclassid",bigid)
Dim ds As DataSet = New DataSet()
strbuyinfo.Fill(ds)
{
Dim objPds As PagedDataSource = New PagedDataSource()
objPds.DataSource = ds.Tables(0).DefaultView
objPds.AllowPaging = True
objPds.PageSize = 5
Dim CurPage As Integer
If Not Request.QueryString("Page") Is Nothing Then
CurPage=Convert.ToInt32(Request.QueryString("Page"))
Else
CurPage=1
End If
objPds.CurrentPageIndex = CurPage-1
lblCurrentPage.Text = "Page: " + CurPage.ToString()
If Not objPds.IsFirstPage Then
lnkPrev.NavigateUrl=Request.CurrentExecutionFilePath + "?id=" + bigid +"&Page=" + Convert.ToString(CurPage-1)
End If
If Not objPds.IsLastPage Then
lnkNext.NavigateUrl=Request.CurrentExecutionFilePath + "?id=" + bigid +"&Page="+ Convert.ToString(CurPage+1)
End If
DlstInfolist.DataSource=objPds
DlstInfolist.DataKeyField="Supply"
DlstInfolist.DataBind()
}
End Sub
[/code]
7.用户密码修改
用户控件:
Button:Btnsubmit
TextBox:TxtNewPwd
存储过程:userpwd_update
C#.Net
[code]
/*
作者:dezai
日期:2006-3-11
用途:用来修改会员的密码
*/
create procedure userpwd_update
@user_ID int,
@user_pwd char(50)
as
update [user]
set
[UserPwd]=@user_pwd
where
[userid]=@user_id
GO
[/code]
c#.Net
[code]
private void Btnsubmit_Click(object sender, System.EventArgs e)
{
if(Page.IsValid)
{
string userid = Request.QueryString["userid"].Trim();
SqlConnection conndb = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
conndb.Open();
SqlCommand Strupdate = new SqlCommand("userpwd_update",conndb);
Strupdate.CommandType = CommandType.StoredProcedure;
Strupdate.Parameters.Add("@user_ID",userid);
Strupdate.Parameters.Add("@user_pwd",TxtNewPwd.Text.Trim());
Strupdate.ExecuteNonQuery();
conndb.Close();
Response.Write("<script language='javascript'>alert('Update succesful!');</script>");
}
else
{
Response.Write("<script language='javascript'>alert('Error!');</script>");}
}
[/code]
VB.Net
[code]
vb.net
Private Sub Btnsubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim userid As String = Request.QueryString("userid").Trim()
Dim conndb As SqlConnection = New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("conn"))
conndb.Open()
Dim Strupdate As SqlCommand = New SqlCommand("userpwd_update",conndb)
Strupdate.CommandType = CommandType.StoredProcedure
Strupdate.Parameters.Add("@user_ID",userid)
Strupdate.Parameters.Add("@user_pwd",TxtNewPwd.Text.Trim())
Strupdate.ExecuteNonQuery()
conndb.Close()
Response.Write("<script language='javascript'>alert('Update succesful!');</script>")
End Sub
[/code]
8.发送E-mail:
用户控件:
Butoon:Button1
TextBox: TxtSubject
Label:LblUsername
c#
注意:要记得引用Jmail组件
[code]
private void Button1_Click(object sender, System.EventArgs e)
{
jmail.Message Jmail=new jmail.Message();
DateTime t=DateTime.Now;
String Subject=TxtSubject.Text.Trim();;
String body="Hello"+LblUsername.Text.Trim();
String FromEmail="eastjazz@163.com";
String ToEmail=LblUseremail.Text.Trim();
//Silent属性:如果设置为true,JMail不会抛出例外错误. JMail. Send( () 会根据操作结果返回true或false
Jmail.Silent=true;
//Jmail创建的日志,前提loging属性设置为true
Jmail.Logging=true;
//字符集,缺省为"US-ASCII"
Jmail.Charset="GB2312";
//信件的contentype. 缺省是"text/plain") : 字符串如果你以HTML格式发送邮件, 改为"text/html"即可。
Jmail.ContentType="text/html";
//添加收件人
Jmail.AddRecipient(ToEmail,"","");
Jmail.From=FromEmail;
//发件人邮件用户名
Jmail.MailServerUserName="dezaiiloveu" ;
//发件人邮件密码
Jmail.MailServerPassWord="dezaistudio" ;
//设置邮件标题
Jmail.Subject=Subject;
//邮件添加附件,(多附件的话,可以再加一条Jmail.AddAttachment( "c:\\test.jpg",true,null);)就可以搞定了。[注]:加了附件,讲把上面的Jmail.ContentType= "text/html";删掉。否则会在邮件里出现乱码。
//邮件内容
Jmail.Body=body+t.ToString();
//Jmail发送的方法
Jmail.Send("smtp.163.com",false);
Jmail.Close() ;
InkBack.Visible=true;
InkBack.NavigateUrl="index.aspx";
}
}
[/code]
VB.Net
[code]
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim Jmail As jmail.Message = New jmail.Message()
Dim t As DateTime = DateTime.Now
Dim Subject As String = TxtSubject.Text.Trim()
Dim body As String = "Hello"+LblUsername.Text.Trim()
Dim FromEmail As String = "eastjazz@163.com"
Dim ToEmail As String = LblUseremail.Text.Trim()
'Silent属性:如果设置为true,JMail不会抛出例外错误. JMail. Send( () 会根据操作结果返回true或false
Jmail.Silent=True
'Jmail创建的日志,前提loging属性设置为true
Jmail.Logging=True
'字符集,缺省为"US-ASCII"
Jmail.Charset="GB2312"
'信件的contentype. 缺省是"text/plain") : 字符串如果你以HTML格式发送邮件, 改为"text/html"即可。
Jmail.ContentType="text/html"
'添加收件人
Jmail.AddRecipient(ToEmail,"","")
Jmail.From=FromEmail
'发件人邮件用户名
Jmail.MailServerUserName="dezaiiloveu"
'发件人邮件密码
Jmail.MailServerPassWord="dezaistudio"
'设置邮件标题
Jmail.Subject=Subject
'邮件添加附件,(多附件的话,可以再加一条Jmail.AddAttachment( "c:\\test.jpg",true,null);)就可以搞定了。[注]:加了附件,讲把上面的Jmail.ContentType= "text/html";删掉。否则会在邮件里出现乱码。
'邮件内容
Jmail.Body=body+t.ToString()
'Jmail发送的方法
Jmail.Send("smtp.163.com",False)
Jmail.Close()
InkBack.Visible=True
InkBack.NavigateUrl="index.aspx"
End Sub
}
[/code]
9.asp.net获取复选框所选的值
c#.net
方法1:
[code]
:
public static string GetCheckBoxListValue(CheckBoxList CBList)
{
string strTemp = "";
for (int i = 0; i < CBList.Items.Count; i++)
{
if (CBList.Items[i].Selected)
{
if (strTemp == "")
{
strTemp = CBList.Items[i].Value;
}
else
{
strTemp += "," + CBList.Items[i].Value;
}
}
}
return strTemp;
}
[/code]
方法2:
[code]
CheckBoxListMessage.Text="";
for (int i=0; i<checkboxlist1.Items.Count; i++)
{
if (checkboxlist1.Items[i].Selected)
{
CheckBoxListMessage.Text += checkboxlist1.Items[i].Text + "<br/>";
}
}
[/code]
10数据库的备份与恢复
[code]
<%@ Page %>
<HTML>
<HEAD>
<title>获取服务器端数据库列表示例</title>
<% @Import Namespace="System.Data" %>
<% @Import Namespace="System.Data.SqlClient" %>
<script language="C#" runat="server">
// 注意本节的数据库连接字符串
string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["conn"];
void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
// 创建连接及执行数据库操作
string db_query = "sp_helpdb";
SqlCommand myCommand = new SqlCommand(db_query, new SqlConnection(ConnStr));
myCommand.Connection.Open();
SqlDataReader dr = myCommand.ExecuteReader();
// 将数据库列表绑定到下拉列表控件(DropDownList)
dbDropDownList.DataSource = dr;
dbDropDownList.DataTextField = "name";
dbDropDownList.DataBind();
//关闭DataReader对象和数据库连接
dr.Close();
myCommand.Connection.Close();
}
}
void dbDropDownList_SelectedIndexChanged(object sender, System.EventArgs e)
{
pathTextBox.Text = @"d:\BACKUP\" + dbDropDownList.SelectedValue + ".bak";
}
void backupButton_Click(object sender, System.EventArgs e)
{
string path = pathTextBox.Text;
string dbname = dbDropDownList.SelectedValue;
string backupSql = "use master;";
backupSql += "backup database @dbname to disk = @path;";
SqlCommand myCommand = new SqlCommand(backupSql, new SqlConnection(ConnStr));
myCommand.Parameters.Add("@dbname", SqlDbType.Char);
myCommand.Parameters["@dbname"].Value = dbname;
myCommand.Parameters.Add("@path", SqlDbType.Char);
myCommand.Parameters["@path"].Value = path;
try
{
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
infoLabel.Text = "备份成功";
}
catch(Exception ex)
{
infoLabel.Text = "备份失败<br/>" + ex.ToString();
}
finally
{
myCommand.Connection.Close();
}
}
void restoreButton_Click(object sender, System.EventArgs e)
{
string path = pathTextBox.Text;
string dbname = dbDropDownList.SelectedValue;
string restoreSql = "use master;";
restoreSql += "restore database @dbname from disk = @path;";
SqlCommand myCommand = new SqlCommand(restoreSql, new SqlConnection(ConnStr));
myCommand.Parameters.Add("@dbname", SqlDbType.Char);
myCommand.Parameters["@dbname"].Value = dbname;
myCommand.Parameters.Add("@path", SqlDbType.Char);
myCommand.Parameters["@path"].Value = path;
try
{
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
infoLabel.Text = "恢复成功";
}
catch(Exception ex)
{
infoLabel.Text = "恢复失败<br/>" + ex.ToString();
}
finally
{
myCommand.Connection.Close();
}
}
</script>
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<h3> </h3>
数据库列表:
<asp:dropdownlist id="dbDropDownList" runat="server" AutoPostBack="True" OnSelectedIndexChanged="dbDropDownList_SelectedIndexChanged"></asp:dropdownlist>
<br>
<br>
请输入备份目录及备份文件名:
<asp:textbox id="pathTextBox" runat="server" Width="224px">
C:\BACKUP\Northwind.bak</asp:textbox>(目录必须存在)
<br>
<br>
<asp:button id="backupButton" runat="server" Font-Size="9pt" Text="备份数据库" OnClick="backupButton_Click"></asp:button>
<asp:button id="restoreButton" runat="server" Font-Size="9pt" Text="恢复数据库" OnClick="restoreButton_Click"></asp:button>
<br>
<br>
<asp:Label id="infoLabel" runat="server"></asp:Label>
</form>
</body>
</HTML>
[/code]
11.C#防注入函数
[code]
public string SafeRequest(string ParaName,int ParaType)
{
//如果是1为数字,0为字符串
string Paravalue="";
Paravalue = ParaName;
if (ParaType==1)
{
if(!(IsNumeric(Paravalue)))
{
Paravalue="0";
}
}
else
{
Paravalue=Paravalue.Replace("'","’");
}
return(Paravalue);
}
public static bool IsNumeric(string strData)
{
float fData;
bool bValid = true;
if(strData.Length>12)
{
bValid = false;
}
else
{
try
{
fData = float.Parse(strData);
}
catch (FormatException)
{
bValid = false;
}
}
return bValid;
}
private void Button1_Click(object sender, System.EventArgs e)
{
Label1.Text=SafeRequest(TextBox1.Text,1);
}
[/code]
暂时先整理到这里,慢慢再补上吧,请大家多多指教:)[em02]
前提准备:
由于项目是采用SQL数据库,所以我们先在web.config中设置好数据库连接
<appSettings>
<add key="Conn" value="Server=(local);Database=dezai;User ID=sa;"></add>
</appSettings>
之后在CS代码中要注意引用
c#
using System.Data.Sqlclient;
using System.Data;
using System.Configuration;
vb.net
Imports System.Data.Sqlclient
Imports System.Data
Imports System.Configuration
以下就是常用的模块
1.会员登陆模块
用户控件:
TextBox:TxtUser 用户名 TxtPwd 密码
Label:LblError 错误提示
存储过程:user_login
[code]
CREATE procedure user_login
@user_name varchar(50),
@user_password varchar(50)
as
select * from userwhere [User_Name] = @User_Name and [User_Pwd] = @User_Password
if @@rowcount>0
begin
update [users] set user_LoginTimes=user_LoginTimes+1 where [User_Name] = @User_Name and [User_Pwd] = @User_Password
end
GO
[/code]
C#.Net
[code]
Private void memberlogin()
{
SqlConnection conndb=new SqlConnection(ConfigurationSettings.AppSettings["Conn"]);
conndb.Open();
SqlCommand cmdlogin = new SqlCommand("User_login",conndb);
cmdlogin.CommandType = CommandType.StoredProcedure;
cmdlogin.Parameters.Add("@user_name",TxtUser.Text.Trim());
cmdlogin.Parameters.Add("@user_password",TxtPwd.Text.Trim());
SqlDataReader reader=cmdlogin.ExecuteReader();
if(reader.Read())
{
Session["user"]=reader["user_id"].ToString();
Session["com"]=reader["com_id"].ToString();
string url;
url="../user/index.aspx?userid="+ Session["userid"] +"&comid="+ Session["comid"] +"";
Response.Redirect(url);
}
else
{
LblError.Text ="Invalid Username or password!Please try again!";
}
}
[/code]
[color=Red]VB.Net[/color]
[code]
Private Sub memberlogin()
Dim conndb As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("Conn"))
conndb.Open()
Dim cmdlogin As SqlCommand = New SqlCommand("User_login",conndb)
cmdlogin.CommandType = CommandType.StoredProcedure
cmdlogin.Parameters.Add("@user_name",TxtUser.Text.Trim())
cmdlogin.Parameters.Add("@user_password",TxtPwd.Text.Trim())
Dim reader As SqlDataReader = cmdlogin.ExecuteReader()
If reader.Read() Then
Session("user")=reader("user_id").ToString()
Session("com")=reader("com_id").ToString()
Dim url As String
url="../user/index.aspx?userid="+ Session("userid") +"&comid="+ Session("comid") +""
Response.Redirect(url)
Else
LblError.Text ="Invalid Username or password!Please try again!"
End If
End Sub
[/code]
2.验证注册用户是否存在
用户控件:
TextBox: TxtMemberID
Label: LblChk
c#代码:
[code]
private bool idcheck()
{
SqlConnection conndb= new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
conndb.Open();
string memberid=TxtMemberId.Text.Trim();
string sql="select User from users where User_Name ='"+memberid+"'";
SqlCommand strchk=new SqlCommand(sql,conndb);
SqlDataReader reader=strchk.ExecuteReader();
if(reader.Read())
{
LblChk.Text="Sorry! this memberid was registed,Please choose another!";
Response.Write("<script>alert(\"Invalid member id\");</script>");
Response.End();
return false;
}
else
{
return true;
}
[/code]
[color=Black]VB.Net 代码[/color]
[code]
private Boolean idcheck()
{
Dim conndb As SqlConnection = New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("conn"))
conndb.Open()
Dim memberid As String = TxtMemberId.Text.Trim()
Dim sql As String = "select User from users where User_Name ='"+memberid+"'"
Dim strchk As SqlCommand = New SqlCommand(sql,conndb)
Dim reader As SqlDataReader = strchk.ExecuteReader()
If reader.Read() Then
LblChk.Text="Sorry! this memberid was registed,Please choose another!"
Response.Write("<script>alert(\"Invalid member id\");</script>")
Response.End()
Return False
Else
Return True
End If
[/code]
3.新用户注册
用户控件:
TextBox:TxtMemberId TxtPwd TxtEmail
ListBox:LstIndustry
存储过程:Users_Insert
[code]
/*
作者:dezai
用途:新进会员的增加注册,同时注册与其相关的企业名录
日期:2006-3-1
*/
CREATE PROCEDURE Users_Insert
@User_Id int output,
@User_Type bit,
@User_Name char(100),
@User_Pwd char(100),
@User_Email char(100)
AS
begin tran
INSERT INTO [Users]
(
[user_type],
[user_name],
[user_pwd],
[user_Email]
)
values
(
@User_Type,
@User_Name,
@User_Pwd,
@User_Email
)
if @@error<>0 goto error
set @user_Id=@@identity
Commit tran
return
ERROR:
set @User_Id = 0
rollback tran
GO
[/code]
c#代码:
[code]
private void reguser()
{
SqlConnection conndb=new SqlConnection(ConfigurationSettings.AppSettings["Conn"]);
SqlCommand cmdinsert = new SqlCommand("Users_Insert",conndb);
cmdinsert.CommandType=CommandType.StoredProcedure;
int intAuthorCount;
cmdinsert.Parameters.Add("@User_Name",TxtMemberId.Text.ToString());
cmdinsert.Parameters.Add("@User_Pwd",TxtPwd.Text.ToString());
cmdinsert.Parameters.Add("@User_Email",TxtEmail.Text.ToString());
cmdinsert.Parameters.Add("@User_Industry",LstIndustry.SelectedValue);
SqlParameter parmReturnValue = new SqlParameter("@User_id", SqlDbType.Int);
parmReturnValue.Direction = ParameterDirection.Output;
cmdinsert.Parameters.Add(parmReturnValue);
conndb.Open();
cmdinsert.ExecuteNonQuery();
intAuthorCount = (int)cmdinsert.Parameters[ "@user_id"].Value;
conndb.Close();
}
[/code]
[color=Red]VB.Net代码[/color]
[code]
Private Sub reguser()
Dim conndb As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("Conn"))
Dim cmdinsert As SqlCommand = New SqlCommand("Users_Insert",conndb)
cmdinsert.CommandType=CommandType.StoredProcedure
Dim intAuthorCount As Integer
cmdinsert.Parameters.Add("@User_Name",TxtMemberId.Text.ToString())
cmdinsert.Parameters.Add("@User_Pwd",TxtPwd.Text.ToString())
cmdinsert.Parameters.Add("@User_Email",TxtEmail.Text.ToString())
cmdinsert.Parameters.Add("@User_Industry",LstIndusTry.SelectedValue)
Dim parmReturnValue As SqlParameter = New SqlParameter("@User_id",SqlDbType.Int)
parmReturnValue.Direction = ParameterDirection.Output
cmdinsert.Parameters.Add(parmReturnValue)
conndb.Open()
cmdinsert.ExecuteNonQuery()
intAuthorCount = CType(cmdinsert.Parameters( "@user_id").Value, Integer)
conndb.Close()
End Sub
[/code]
4.图片上传
c#.Net
[code]private void uppic()
{
string mPath;
string imagePath;
string imageType;
string imageName;
DateTime dtmDate;
dtmDate = DateTime.Now;
if(""!=this.fileup.PostedFile.FileName)
{
imagePath = this.fileup.PostedFile.FileName;
imageType = imagePath.Substring(imagePath.LastIndexOf(".")+1);
imageName=imagePath.Substring(imagePath.LastIndexOf("\\")+1);
if("jpg" != imageType && "gif" !=imageType && "png" !=imageType && "PNG" !=imageType && "GIF" !=imageType && "JPG" !=imageType)
{
Response.Write("<script language='javascript'>alert('sorry!Please choose *.jpg or *.gif or *.png');</script>");
return;
}
else
{
try
{
mPath=Server.MapPath("upfile");
this.fileup.PostedFile.SaveAs(mPath+"\\"+"dezaistudio"+dtmDate.ToString("yyyyMMddhhmmss")+imageName);
this.ImageSmall.ImageUrl = "dezaistudio"+dtmDate.ToString("yyyyMMddhhmmss")+imageName;
Response.Write("<script language='javascript'>alert('upload succesful');</script>");
TxtPicPath.Text = this.ImageSmall.ImageUrl.ToString().Trim();
}
catch
{
Response.Write("error");
}
}
}
}
[/code]
[color=Red]VB.Net代码[/color]
[code]
Private Sub uppic()
Dim mPath As String
Dim imagePath As String
Dim imageType As String
Dim imageName As String
Dim dtmDate As DateTime
dtmDate = DateTime.Now
If ""<>Me.fileup.PostedFile.FileName Then
imagePath = Me.fileup.PostedFile.FileName
imageType = imagePath.Substring(imagePath.LastIndexOf(".")+1)
imageName=imagePath.Substring(imagePath.LastIndexOf("\\")+1)
If "jpg" <> imageType And "gif" <>imageType And "png" <>imageType And "PNG" <>imageType And "GIF" <>imageType And "JPG" <>imageType Then
Response.Write("<script language='javascript'>alert('sorry!Please choose *.jpg or *.gif or *.png');</script>")
Return
Else
Try
mPath=Server.MapPath("upfile")
Me.fileup.PostedFile.SaveAs(mPath+"\\"+"dezaistudio"+dtmDate.ToString("yyyyMMddhhmmss")+imageName)
Me.ImageSmall.ImageUrl = "dezaistudio"+dtmDate.ToString("yyyyMMddhhmmss")+imageName
Response.Write("<script language='javascript'>alert('upload succesful');</script>")
TxtPicPath.Text = Me.ImageSmall.ImageUrl.ToString().Trim()
Catch
Response.Write("error")
End Try
End If
End If
End Sub
[/code]
5.DataList分页(其实Repeart也可采用这个,只是改一下控件名而已)
用户控件
DataList: DlstInfolist
Label:lblCurrentPage
HyperLink:lnkNext LnkPrev
存储过程:supplyinfo_select
[code]
/*
查询大类下所有的supplyinfo
2006-4-10
*/
create procedure supplyinfo_select
@bigclassid int
as
select * from supply
where
Supply_CatID=@bigclassid
GO
[/code]
c#.Net
[code]
private void dlstsupplyinfolist()
{
SqlConnection conndb = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
conndb.Open();
string bigid=Request.QueryString["bigid"].Trim();
SqlDataAdapter strbuyinfo = new SqlDataAdapter("supplyinfo_select",conndb);
strbuyinfo.SelectCommand.CommandType = CommandType.StoredProcedure;
strbuyinfo.SelectCommand.Parameters.Add("@bigclassid",bigid);
DataSet ds = new DataSet();
strbuyinfo.Fill(ds);
{
PagedDataSource objPds = new PagedDataSource();
objPds.DataSource = ds.Tables[0].DefaultView;
objPds.AllowPaging = true;
objPds.PageSize = 5;
int CurPage;
if (Request.QueryString["Page"] != null)
CurPage=Convert.ToInt32(Request.QueryString["Page"]);
else
CurPage=1;
objPds.CurrentPageIndex = CurPage-1;
lblCurrentPage.Text = "Page: " + CurPage.ToString();
if (!objPds.IsFirstPage)
lnkPrev.NavigateUrl=Request.CurrentExecutionFilePath + "?id=" + bigid +"&Page=" + Convert.ToString(CurPage-1);
if (!objPds.IsLastPage)
lnkNext.NavigateUrl=Request.CurrentExecutionFilePath + "?id=" + bigid +"&Page="+ Convert.ToString(CurPage+1);
DlstInfolist.DataSource=objPds;
DlstInfolist.DataKeyField="Supply";
DlstInfolist.DataBind();
}
}
[/code]
VB.Net
[code]
Private Sub dlstsupplyinfolist()
Dim conndb As SqlConnection = New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("conn"))
conndb.Open()
Dim bigid As String = Request.QueryString("bigid").Trim()
Dim strbuyinfo As SqlDataAdapter = New SqlDataAdapter("supplyinfo_select",conndb)
strbuyinfo.SelectCommand.CommandType = CommandType.StoredProcedure
strbuyinfo.SelectCommand.Parameters.Add("@bigclassid",bigid)
Dim ds As DataSet = New DataSet()
strbuyinfo.Fill(ds)
{
Dim objPds As PagedDataSource = New PagedDataSource()
objPds.DataSource = ds.Tables(0).DefaultView
objPds.AllowPaging = True
objPds.PageSize = 5
Dim CurPage As Integer
If Not Request.QueryString("Page") Is Nothing Then
CurPage=Convert.ToInt32(Request.QueryString("Page"))
Else
CurPage=1
End If
objPds.CurrentPageIndex = CurPage-1
lblCurrentPage.Text = "Page: " + CurPage.ToString()
If Not objPds.IsFirstPage Then
lnkPrev.NavigateUrl=Request.CurrentExecutionFilePath + "?id=" + bigid +"&Page=" + Convert.ToString(CurPage-1)
End If
If Not objPds.IsLastPage Then
lnkNext.NavigateUrl=Request.CurrentExecutionFilePath + "?id=" + bigid +"&Page="+ Convert.ToString(CurPage+1)
End If
DlstInfolist.DataSource=objPds
DlstInfolist.DataKeyField="Supply"
DlstInfolist.DataBind()
}
End Sub
[/code]
7.用户密码修改
用户控件:
Button:Btnsubmit
TextBox:TxtNewPwd
存储过程:userpwd_update
C#.Net
[code]
/*
作者:dezai
日期:2006-3-11
用途:用来修改会员的密码
*/
create procedure userpwd_update
@user_ID int,
@user_pwd char(50)
as
update [user]
set
[UserPwd]=@user_pwd
where
[userid]=@user_id
GO
[/code]
c#.Net
[code]
private void Btnsubmit_Click(object sender, System.EventArgs e)
{
if(Page.IsValid)
{
string userid = Request.QueryString["userid"].Trim();
SqlConnection conndb = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
conndb.Open();
SqlCommand Strupdate = new SqlCommand("userpwd_update",conndb);
Strupdate.CommandType = CommandType.StoredProcedure;
Strupdate.Parameters.Add("@user_ID",userid);
Strupdate.Parameters.Add("@user_pwd",TxtNewPwd.Text.Trim());
Strupdate.ExecuteNonQuery();
conndb.Close();
Response.Write("<script language='javascript'>alert('Update succesful!');</script>");
}
else
{
Response.Write("<script language='javascript'>alert('Error!');</script>");}
}
[/code]
VB.Net
[code]
vb.net
Private Sub Btnsubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim userid As String = Request.QueryString("userid").Trim()
Dim conndb As SqlConnection = New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("conn"))
conndb.Open()
Dim Strupdate As SqlCommand = New SqlCommand("userpwd_update",conndb)
Strupdate.CommandType = CommandType.StoredProcedure
Strupdate.Parameters.Add("@user_ID",userid)
Strupdate.Parameters.Add("@user_pwd",TxtNewPwd.Text.Trim())
Strupdate.ExecuteNonQuery()
conndb.Close()
Response.Write("<script language='javascript'>alert('Update succesful!');</script>")
End Sub
[/code]
8.发送E-mail:
用户控件:
Butoon:Button1
TextBox: TxtSubject
Label:LblUsername
c#
注意:要记得引用Jmail组件
[code]
private void Button1_Click(object sender, System.EventArgs e)
{
jmail.Message Jmail=new jmail.Message();
DateTime t=DateTime.Now;
String Subject=TxtSubject.Text.Trim();;
String body="Hello"+LblUsername.Text.Trim();
String FromEmail="eastjazz@163.com";
String ToEmail=LblUseremail.Text.Trim();
//Silent属性:如果设置为true,JMail不会抛出例外错误. JMail. Send( () 会根据操作结果返回true或false
Jmail.Silent=true;
//Jmail创建的日志,前提loging属性设置为true
Jmail.Logging=true;
//字符集,缺省为"US-ASCII"
Jmail.Charset="GB2312";
//信件的contentype. 缺省是"text/plain") : 字符串如果你以HTML格式发送邮件, 改为"text/html"即可。
Jmail.ContentType="text/html";
//添加收件人
Jmail.AddRecipient(ToEmail,"","");
Jmail.From=FromEmail;
//发件人邮件用户名
Jmail.MailServerUserName="dezaiiloveu" ;
//发件人邮件密码
Jmail.MailServerPassWord="dezaistudio" ;
//设置邮件标题
Jmail.Subject=Subject;
//邮件添加附件,(多附件的话,可以再加一条Jmail.AddAttachment( "c:\\test.jpg",true,null);)就可以搞定了。[注]:加了附件,讲把上面的Jmail.ContentType= "text/html";删掉。否则会在邮件里出现乱码。
//邮件内容
Jmail.Body=body+t.ToString();
//Jmail发送的方法
Jmail.Send("smtp.163.com",false);
Jmail.Close() ;
InkBack.Visible=true;
InkBack.NavigateUrl="index.aspx";
}
}
[/code]
VB.Net
[code]
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim Jmail As jmail.Message = New jmail.Message()
Dim t As DateTime = DateTime.Now
Dim Subject As String = TxtSubject.Text.Trim()
Dim body As String = "Hello"+LblUsername.Text.Trim()
Dim FromEmail As String = "eastjazz@163.com"
Dim ToEmail As String = LblUseremail.Text.Trim()
'Silent属性:如果设置为true,JMail不会抛出例外错误. JMail. Send( () 会根据操作结果返回true或false
Jmail.Silent=True
'Jmail创建的日志,前提loging属性设置为true
Jmail.Logging=True
'字符集,缺省为"US-ASCII"
Jmail.Charset="GB2312"
'信件的contentype. 缺省是"text/plain") : 字符串如果你以HTML格式发送邮件, 改为"text/html"即可。
Jmail.ContentType="text/html"
'添加收件人
Jmail.AddRecipient(ToEmail,"","")
Jmail.From=FromEmail
'发件人邮件用户名
Jmail.MailServerUserName="dezaiiloveu"
'发件人邮件密码
Jmail.MailServerPassWord="dezaistudio"
'设置邮件标题
Jmail.Subject=Subject
'邮件添加附件,(多附件的话,可以再加一条Jmail.AddAttachment( "c:\\test.jpg",true,null);)就可以搞定了。[注]:加了附件,讲把上面的Jmail.ContentType= "text/html";删掉。否则会在邮件里出现乱码。
'邮件内容
Jmail.Body=body+t.ToString()
'Jmail发送的方法
Jmail.Send("smtp.163.com",False)
Jmail.Close()
InkBack.Visible=True
InkBack.NavigateUrl="index.aspx"
End Sub
}
[/code]
9.asp.net获取复选框所选的值
c#.net
方法1:
[code]
:
public static string GetCheckBoxListValue(CheckBoxList CBList)
{
string strTemp = "";
for (int i = 0; i < CBList.Items.Count; i++)
{
if (CBList.Items[i].Selected)
{
if (strTemp == "")
{
strTemp = CBList.Items[i].Value;
}
else
{
strTemp += "," + CBList.Items[i].Value;
}
}
}
return strTemp;
}
[/code]
方法2:
[code]
CheckBoxListMessage.Text="";
for (int i=0; i<checkboxlist1.Items.Count; i++)
{
if (checkboxlist1.Items[i].Selected)
{
CheckBoxListMessage.Text += checkboxlist1.Items[i].Text + "<br/>";
}
}
[/code]
10数据库的备份与恢复
[code]
<%@ Page %>
<HTML>
<HEAD>
<title>获取服务器端数据库列表示例</title>
<% @Import Namespace="System.Data" %>
<% @Import Namespace="System.Data.SqlClient" %>
<script language="C#" runat="server">
// 注意本节的数据库连接字符串
string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["conn"];
void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
// 创建连接及执行数据库操作
string db_query = "sp_helpdb";
SqlCommand myCommand = new SqlCommand(db_query, new SqlConnection(ConnStr));
myCommand.Connection.Open();
SqlDataReader dr = myCommand.ExecuteReader();
// 将数据库列表绑定到下拉列表控件(DropDownList)
dbDropDownList.DataSource = dr;
dbDropDownList.DataTextField = "name";
dbDropDownList.DataBind();
//关闭DataReader对象和数据库连接
dr.Close();
myCommand.Connection.Close();
}
}
void dbDropDownList_SelectedIndexChanged(object sender, System.EventArgs e)
{
pathTextBox.Text = @"d:\BACKUP\" + dbDropDownList.SelectedValue + ".bak";
}
void backupButton_Click(object sender, System.EventArgs e)
{
string path = pathTextBox.Text;
string dbname = dbDropDownList.SelectedValue;
string backupSql = "use master;";
backupSql += "backup database @dbname to disk = @path;";
SqlCommand myCommand = new SqlCommand(backupSql, new SqlConnection(ConnStr));
myCommand.Parameters.Add("@dbname", SqlDbType.Char);
myCommand.Parameters["@dbname"].Value = dbname;
myCommand.Parameters.Add("@path", SqlDbType.Char);
myCommand.Parameters["@path"].Value = path;
try
{
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
infoLabel.Text = "备份成功";
}
catch(Exception ex)
{
infoLabel.Text = "备份失败<br/>" + ex.ToString();
}
finally
{
myCommand.Connection.Close();
}
}
void restoreButton_Click(object sender, System.EventArgs e)
{
string path = pathTextBox.Text;
string dbname = dbDropDownList.SelectedValue;
string restoreSql = "use master;";
restoreSql += "restore database @dbname from disk = @path;";
SqlCommand myCommand = new SqlCommand(restoreSql, new SqlConnection(ConnStr));
myCommand.Parameters.Add("@dbname", SqlDbType.Char);
myCommand.Parameters["@dbname"].Value = dbname;
myCommand.Parameters.Add("@path", SqlDbType.Char);
myCommand.Parameters["@path"].Value = path;
try
{
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
infoLabel.Text = "恢复成功";
}
catch(Exception ex)
{
infoLabel.Text = "恢复失败<br/>" + ex.ToString();
}
finally
{
myCommand.Connection.Close();
}
}
</script>
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<h3> </h3>
数据库列表:
<asp:dropdownlist id="dbDropDownList" runat="server" AutoPostBack="True" OnSelectedIndexChanged="dbDropDownList_SelectedIndexChanged"></asp:dropdownlist>
<br>
<br>
请输入备份目录及备份文件名:
<asp:textbox id="pathTextBox" runat="server" Width="224px">
C:\BACKUP\Northwind.bak</asp:textbox>(目录必须存在)
<br>
<br>
<asp:button id="backupButton" runat="server" Font-Size="9pt" Text="备份数据库" OnClick="backupButton_Click"></asp:button>
<asp:button id="restoreButton" runat="server" Font-Size="9pt" Text="恢复数据库" OnClick="restoreButton_Click"></asp:button>
<br>
<br>
<asp:Label id="infoLabel" runat="server"></asp:Label>
</form>
</body>
</HTML>
[/code]
11.C#防注入函数
[code]
public string SafeRequest(string ParaName,int ParaType)
{
//如果是1为数字,0为字符串
string Paravalue="";
Paravalue = ParaName;
if (ParaType==1)
{
if(!(IsNumeric(Paravalue)))
{
Paravalue="0";
}
}
else
{
Paravalue=Paravalue.Replace("'","’");
}
return(Paravalue);
}
public static bool IsNumeric(string strData)
{
float fData;
bool bValid = true;
if(strData.Length>12)
{
bValid = false;
}
else
{
try
{
fData = float.Parse(strData);
}
catch (FormatException)
{
bValid = false;
}
}
return bValid;
}
private void Button1_Click(object sender, System.EventArgs e)
{
Label1.Text=SafeRequest(TextBox1.Text,1);
}
[/code]
暂时先整理到这里,慢慢再补上吧,请大家多多指教:)[em02]