新建项目
选择 ASP.NET Web 应用程序,项目名称为 WebFormDemo

右键项目选择“添加”->“新建项”

选择 Web 窗体

点击“设计”

选择“工具箱”,用鼠标拖动“Button”和"TextBox"到设计页面

拖动后显示如下:


在“设计”界面中双击“Button”,会自动在 cs 文件中添加 Button 点击事件,如下图所示:

添加事件内容

测试结果:
文本框输入任意内容,如我输入字符串“c”

查看SQL保存结果:

代码实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string strtxt = TextBox1.Text;
System.Data.SqlClient.SqlConnection SqlCnn = new System.Data.SqlClient.SqlConnection("Data Source=JOHN;Initial Catalog=webservice;User ID=sa;Password=12345678;");
//打开数据库连接
SqlCnn.Open();
string sqlstr = "insert into dbo.homework (datetime,homeworkcontent) values('"+DateTime.Now+"','" + strtxt + "')";
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.Connection = SqlCnn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = sqlstr;
//执行
cmd.ExecuteNonQuery();
//关闭数据库
SqlCnn.Close();
}
}
}