按照下图添加控件
确保你的数据库中有northwind数据库,以及表Region,没有的话就自己建立一个吧
按照下图添加控件
最后的所有文件
确保你的数据库中有northwind数据库,以及表Region,没有的话就自己建立一个吧
1 新建存储过程:
CREATE PROCEDURE insert_Region @RegionID int,@RegionDescription nchar(50) AS insert into Region(RegionID,RegionDescription) values(@RegionID,@RegionDescription)
2:添加一个DB类:
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.SqlClient; /// <summary> /// DB 的摘要说明 /// </summary> public class DB { public DB() { } public static SqlConnection createCon() { return new SqlConnection("server=.;database=northwind;uid=sa;pwd=;"); } }
default.aspx
<%@ Page Language="C#" 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:GridView ID="GridView1" runat="server"> </asp:GridView> <br /> ID:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <br /> Desc:<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br /> <asp:Button ID="Button1" runat="server" Text="调用存储过程" OnClick="Button1_Click" /></div> </form> </body> </html>
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; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { bind(); } } public void bind() { string sql = "select * from Region"; SqlConnection con = DB.createCon();//创建数据库连接 SqlDataAdapter sda = new SqlDataAdapter(sql, con); DataSet ds = new DataSet(); con.Open(); sda.Fill(ds,"Region"); GridView1.DataSource = ds; GridView1.DataBind();//绑定数据 con.Close(); } protected void Button1_Click(object sender, EventArgs e) { SqlConnection con = DB.createCon(); con.Open(); SqlCommand sqlCmd = new SqlCommand("insert_Region", con);//调用的存储过程 sqlCmd.CommandType = CommandType.StoredProcedure;//使用存储过程方式 sqlCmd.Parameters.Add("@RegionID", SqlDbType.Int).Value = TextBox1.Text.Trim();//添加参数 sqlCmd.Parameters.Add("@RegionDescription", SqlDbType.NChar,50).Value = TextBox2.Text.Trim(); sqlCmd.ExecuteNonQuery();//执行 con.Close(); bind(); } }