我有一个名为Table1的sql表,它有3列 - 名称(字符串),值(浮点),日期(日期时间)。我希望在单击Button1时填充表格。 所以我有一个功能"插入"填充表格和按钮点击功能,从两个文本框中获取值。问题是,当我打电话"插入"像解释它的函数给了我一些参数无效的错误消息
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Services;
using System.Configuration;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public void Insert(string Name, float Value, DateTime DateTime)
{
string connectionString = ConfigurationManager.ConnectionStrings["FatherDB"].ToString();
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("Insert into Table1 ((Name) values(@Name) ,(Value) values(@Value),(Date) values(@Date))", con))
{
con.Open();
cmd.Parameters.AddWithValue("@Name", Name);
cmd.Parameters.AddWithValue("@Value", Value);
cmd.Parameters.AddWithValue("@Date", DateTime);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
DateTime z = DateTime.Now;
string Name = Box1.ToString();
float Value = float.Parse(Box2.Text);
Insert(Name, Value, z);
//Insert(Name, Value, z); want to call the function with parameters from text boxes
}
}
}
Html页面
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<script type="text/javascript">
</script>
<style>
.TBox{
position:relative;
height:30px;
width:150px;
margin-left:10px;
}
.Div {
margin-top:50px;
}
</style>
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div class="Div">
<asp:TextBox id="Box1" CssClass="TBox" runat="server">
</asp:TextBox>
<asp:TextBox id="Box2" CssClass="TBox" runat="server">
</asp:TextBox>
<asp:Button id="Button1" CssClass="TBox" runat="server" Text="Enter" />
</div>
</form>
</body>
</html>
答案 0 :(得分:5)
你的插入语句应该是错误的:
"Insert into Table1 (Name,Value,[Date]) values(@Name, @Value,@Date)"
所以替换这个:
using (SqlCommand cmd = new SqlCommand("Insert into Table1 ((Name) values(@Name) ,(Value) values(@Value),(Date) values(@Date))", con))
使用:
using (SqlCommand cmd = new SqlCommand("Insert into Table1 (Name,Value,[Date]) values(@Name, @Value,@Date)", con))