时间:2021-07-01 10:21:17 帮助过:64人阅读
<%@ Page Language="C#" Debug="true" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="姓名"></asp:Label>
<asp:TextBox ID="tbxName" runat="server"></asp:TextBox><br />
<br />
<asp:Label ID="Label2" runat="server" Text="成绩"></asp:Label>
<asp:TextBox ID="tbxScore" runat="server"></asp:TextBox><br />
<br />
<asp:Button ID="btnInsert" runat="server" OnClick="btnInsert_Click" Text="插入数据" />
</div>
</form>
</body>
</html>
3、双击default.aspx进入default.aspx.cs,代码如下:
default.aspx.cs的主要代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnInsert_Click(object sender, EventArgs e)
{
student myStu = new student();
myStu.sname = this.tbxName.Text;
myStu.score = Convert.ToInt32(this.tbxScore.Text);
int i= MyClass.insertScore(myStu);
if (i == 1)
{
Response.Write("插入成功");
}
else
{
Response.Write("插入失败");
}
}
}
4、在App_Code建立两个类,一个是MyClass.cs,另一个是student.cs,
MyClass.cs的主要代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
/// <summary>
/// MyClass 的摘要说明
/// </summary>
public class MyClass
{
public MyClass()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public static OleDbConnection creatCon()
{//Data Source=后面请写你自己的数据库的绝对路径
return new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:/Documents and Settings/nan/My Documents/Visual Studio 2005/WebSites/WebSite3/App_Data/myData.mdb");
}
public static int insertScore(student myStu)
{
string cmdText = "insert into student(sname,score) values('" + myStu.sname + "','" + myStu.score + "')";
OleDbConnection con = MyClass.creatCon();
con.Open();
OleDbCommand cmd = new OleDbCommand(cmdText, con);
int result = Convert.ToInt32(cmd.ExecuteNonQuery());
con.Close();
return result;
}
}
student.cs的主要代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
/// <summary>
/// student 的摘要说明
/// </summary>
public class student
{
public string sname;
public int score;
}