尝试从TextBoxes将值插入数据库

时间:2012-05-03 20:18:06

标签: c# sql-server ado.net

我对这一点感到非常难过,而且我是C#的新手,所以也许你们中的一个好人可以帮助我。我正在尝试使用ADO.NET从表单字段更新数据库。

基本上,我得到的错误是我试图将空值插入数据库。错误的确切文本是:

System.ArgumentNullException: The SqlParameterCollection only accepts non-null SqlParameter type objects.

以下是我尝试使用的页面背后的代码:

private void ExecuteInsert(string firstName, string lastName, string emailAddress, string city, string phone)
{
    SqlConnection conn = new SqlConnection(GetConnectionString());
    string sql = "INSERT INTO contactInfo (firstName, lastName, emailAddress, city, phone) VALUES "
                + " (@firstName, @lastName, @emailAddress, @city, @phone)";

    try
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        SqlParameter[] param = new SqlParameter[6];
        param[0] = new SqlParameter("@firstName", SqlDbType.NVarChar, 25);
        param[1] = new SqlParameter("@lastName", SqlDbType.NVarChar, 25);
        param[2] = new SqlParameter("@emailAddress", SqlDbType.NVarChar, 30);
        param[3] = new SqlParameter("@city", SqlDbType.NVarChar, 50);
        param[4] = new SqlParameter("@phone", SqlDbType.Int, 10);

        param[0].Value = firstName;
        param[1].Value = lastName;
        param[2].Value = emailAddress;
        param[3].Value = city;
        param[4].Value = phone;

        for (int i = 0; i < param.Length; i++)
        {
                cmd.Parameters.Add(param[i]);
        }

        cmd.CommandType = CommandType.Text;
        cmd.ExecuteNonQuery();
    }
    catch (System.Data.SqlClient.SqlException ex)
    {
        string msg = "Insert Error:";
        msg += ex.Message;
        throw new Exception(msg);
    }
    finally
    {
        conn.Close();
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    if (firstName.Text != null)
    {
        //call the method to execute insert to the database
        ExecuteInsert(firstName.Text,
                      lastName.Text,
                      emailAddress.Text,
                      city.Text,
                      phone.Text);
        Response.Write("Record was successfully added!");
        ClearControls(Page);
    }
    else
    {
        Response.Write("Please enter your name");
    }
}

public static void ClearControls(Control Parent)
{

    if (Parent is TextBox)
    { (Parent as TextBox).Text = string.Empty; }
    else
    {
        foreach (Control c in Parent.Controls)
            ClearControls(c);
    }
}

如果还有其他方式我应该这样做,我很乐意听到它。我似乎无法在网上找到好的信息。

2 个答案:

答案 0 :(得分:2)

这一行:

SqlParameter[] param = new SqlParameter[6];

应该是(数组太大而你没有设置最后一个参数):

SqlParameter[] param = new SqlParameter[5];

答案 1 :(得分:0)

更改

SqlParameter[] param = new SqlParameter[6];

SqlParameter[] param = new SqlParameter[5];

您可以直接将参数添加到cmd.Parameters,而无需创建临时数组。