执行效果:
前台代码:
<%@ 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>使用Command对象添加数据</title>
<style >
body:{margin-top:0px}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style=" font-size :9pt">
<tr>
<td>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</td>
</tr>
<tr>
<td>
请输入公司名:<br />
<asp:TextBox ID="bukrs" runat="server" Width="78px"></asp:TextBox><asp:TextBox
ID="text" runat="server"></asp:TextBox>
<asp:TextBox ID="addr" runat="server"></asp:TextBox>
<asp:Button ID="btnAdd" runat="server" Text="添加" OnClick="btnAdd_Click" /></td>
</tr>
</table>
</div>
</form>
</body>
</html>
后台代码:
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)
{
this.bind();
}
}
public SqlConnection GetConnection()
{
string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
SqlConnection myConn = new SqlConnection(myStr);
return myConn;
}
protected void bind()
{
SqlConnection myConn = GetConnection();
myConn.Open();
string sqlStr = "select * from t001 ";
SqlDataAdapter myDa = new SqlDataAdapter(sqlStr, myConn);
DataSet myDs = new DataSet();
myDa.Fill(myDs);
GridView1.DataSource = myDs;
GridView1.DataBind();
myDa.Dispose();
myDs.Dispose();
myConn.Close();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (this.bukrs.Text != "")
{
SqlConnection myConn = GetConnection();
myConn.Open();
string sqlStr = "insert into t001(bukrs,text,addr) values('" + this.bukrs.Text.Trim() + "', '" + this.text.Text.Trim() + "','" + this.addr.Text.Trim() + "')";
SqlCommand myCmd = new SqlCommand(sqlStr, myConn);
myCmd.ExecuteNonQuery();
myConn.Close();
this.bind();
}
else
this.bind();
}
}
配置代码:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="ConnectionString" value="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\DataBase\sap.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"/>
</appSettings>
<connectionStrings/>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<authentication mode="Windows"/>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
</system.web>
</configuration>