ASP.net使用表单将数据插入sql server表
嗨 在php中,我会做一个带有动作的表单,比如一个process.php页面,在该页面中,我会获取post值,并使用mysql\u查询进行插入。 现在我迷路了,我正在尝试使用visual studio 2010通过sql server 2008在ASP.net中创建一个from并进行插入 我在App_数据文件夹中定义了一个sql数据库。 基本上我需要的(除非有更好的方法)是:ASP.net使用表单将数据插入sql server表,asp.net,sql-server,forms,insert,Asp.net,Sql Server,Forms,Insert,嗨 在php中,我会做一个带有动作的表单,比如一个process.php页面,在该页面中,我会获取post值,并使用mysql\u查询进行插入。 现在我迷路了,我正在尝试使用visual studio 2010通过sql server 2008在ASP.net中创建一个from并进行插入 我在App_数据文件夹中定义了一个sql数据库。 基本上我需要的(除非有更好的方法)是: 如何获取post值 如何将它们插入数据库中 谢谢。简单,使用设计器创建一个简单的asp页面(仅用于开头),让我们假设主体
谢谢。简单,使用设计器创建一个简单的asp页面(仅用于开头),让我们假设主体如下所示:
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" />
</p>
</form>
</body>
现在,当您单击按钮时,将调用此方法。因为ASP是面向对象的,所以可以将页面视为实际的类,对象将保存实际的当前数据
因此,例如,如果您想访问TextBox1
中的文本,只需在C代码中调用该对象:
同样,您可以在事件发生时填充对象
现在您已经在文本框中发布了用户的数据,您可以使用常规的C#SQL连接将数据添加到您的数据库中。关于如何执行此操作,网上有大量示例代码 下面仅举一个例子说明如何做到这一点: 您可以在以下标记之间定义文本框:
<form id="form1" runat="server">
或者,您可以在“设计”视图中双击该按钮
下面是一个非常快速的代码示例,可以在button click事件(codebehind)中插入到表中
您可能会发现此资源非常有用:
String firstBox = TextBox1.Text;
<form id="form1" runat="server">
<asp:TextBox ID="TxtName" runat="server"></asp:TextBox>
<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
}
}
}