-1

此代码用于按钮:
但每次我运行它时都会说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)
    {

    }
}
4

1 回答 1

-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 = "";
    }
}
于 2013-04-17T00:15:14.380 回答