网上有大量关于如何执行此操作的示例代码。
以下只是如何执行此操作的一个示例:http://geekswithblogs.net/dotNETvinz/archive/2009/04/30/creating-a-simple-registration-form-in-asp.net.aspx http://geekswithblogs.net/dotNETvinz/archive/2009/04/30/creating-a-simple-registration-form-in-asp.net.aspx
您定义以下标记之间的文本框:
<form id="form1" runat="server">
您创建文本框并将它们定义为 runat="server" ,如下所示:
<asp:TextBox ID="TxtName" runat="server"></asp:TextBox>
定义一个按钮来处理你的逻辑,如下所示(注意onclick):
<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
在后面的代码中,您可以通过定义名为的方法来定义用户单击按钮时希望服务器执行的操作
protected void Button1_Click(object sender, EventArgs e)
或者您只需双击设计视图中的按钮即可。
这是一个非常快速的代码示例,用于在按钮单击事件中插入表(代码隐藏)
protected void Button1_Click(object sender, EventArgs e)
{
string name = TxtName.Text; // Scrub user data
string connString = ConfigurationManager.ConnectionStrings["yourconnstringInWebConfig"].ConnectionString;
SqlConnection conn = null;
try
{
conn = new SqlConnection(connString);
conn.Open();
using(SqlCommand cmd = new SqlCommand())
{
cmd.Conn = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO dummyTable(name) Values (@var)";
cmd.Parameters.AddWithValue("@var", name);
int rowsAffected = cmd.ExecuteNonQuery();
if(rowsAffected ==1)
{
//Success notification
}
else
{
//Error notification
}
}
}
catch(Exception ex)
{
//log error
//display friendly error to user
}
finally
{
if(conn!=null)
{
//cleanup connection i.e close
}
}
}