我刚学.NET不久,终于知道怎么添加数据了,分享给那些刚学.NET的人。我用(C#.NET+SQL2005)
前台代码是:
<table id="divlist">
<tr>
<td>标题新闻:</td>
<td>
<asp:TextBox ID="AddName" runat="server"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ControlToValidate="AddName" ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
新闻内容:
</td>
<td>
<asp:TextBox ID="AddBody" runat="server"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ControlToValidate="AddBody" ID="RequiredFieldValidator2" runat="server" ErrorMessage="RequiredFieldValidator">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
新闻时间:
</td>
<td>
<asp:TextBox ID="AddTime" runat="server"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtender1" runat="server" Format="yyyy-MM-dd" TargetControlID="AddTime">
</asp:CalendarExtender>
</td>
<td>
</td>
</tr>
<tr>
<td>
<asp:Button ID="AddButton" runat="server" Text="添加" οnclick="AddButton_Click" />
</td>
</tr>
</table>
后台代码是:
protected void AddButton_Click(object sender, EventArgs e)
{
String StrConn = "Data Source=MARS-5AB441B1A1;Initial Catalog=ReleaseNews;Integrated Security=True;Pooling=False";
SqlConnection conn = new SqlConnection(StrConn);
String StrCmd = "Insert into News" + "(NewsName,NewsBody,NewsTime)" + "Values" + "(@NewsName,@NewsBody,@NewsTime)";
SqlCommand cmd = new SqlCommand(StrCmd,conn);//此处需要使cmd和conn关联
cmd.Parameters.Add("NewsName", SqlDbType.VarChar);
cmd.Parameters.Add("NewsBody", SqlDbType.VarChar);
cmd.Parameters.Add("NewsTime", SqlDbType.DateTime);
cmd.Parameters["NewsName"].Value = AddName.Text.Trim();
cmd.Parameters["NewsBody"].Value = AddBody.Text.Trim();
cmd.Parameters["NewsTime"].Value = AddTime.Text.Trim();
try
{
if (conn.State == ConnectionState.Closed)
{ conn.Open(); }
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
Response.Write("fause");
}
finally
{
if (conn.State == ConnectionState.Open)
{ conn.Close(); }
}
//Response.Write("OK");
Response.Redirect("ReleaseNews.aspx");
}
记得要加上using System.Data.SqlClient;