尝试打开SqlConnection时ArgumentException

时间:2013-04-16 10:18:04

标签: asp.net sql-server ado.net

此代码用于按钮:
但每次我说它都是ArgumentException was unhandled by user code

这是一个查找数据库以查看是否有足够墨水的网站。

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.Configuration;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    {
        con.Open();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("insert into Toner Values('"+txtFname.Text+"','"+txtLname.Text+"','"+TxtCity.Text+"')",con);
        cmd.ExecuteNonQuery();
        con.Close();
        Label1.Visible = true;
            Label1.Text = "Indsætning succesfuld!!!";
        TxtCity.Text = "";
        txtFname.Text = "";
        txtLname.Text = "";
    }
    protected void TextBox3_TextChanged(object sender, EventArgs e)
    {

    }
}

1 个答案:

答案 0 :(得分:-1)

我最好的猜测是TxtCity应为txtCity

试试这个:

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.Configuration;

public partial class _Default : System.Web.UI.Page
{

    protected void Button1_Click(object sender, EventArgs e)
    {
        string query = "insert into Toner Values (@Fname, @Lname, @City)";
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString);
        SqlCommand cmd = new SqlCommand(query, con);
        //Use parameterized query to prevent SQL injection
        cmd.Parameters.Add("Fname", SqlDbType.VarChar, 50).Value = txtFname.Text;
        cmd.Parameters.Add("Lname", SqlDbType.VarChar, 50).Value = txtLname.Text;
        //C# is case-sensitive... is it txtCity or TxtCity?
        cmd.Parameters.Add("City", SqlDbType.VarChar, 50).Value = TxtCity.Text;
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        Label1.Visible = true;
        Label1.Text = "Indsætning succesfuld!!!";
        TxtCity.Text = "";
        txtFname.Text = "";
        txtLname.Text = "";
    }
}