C#SQL Server更新,如果不存在,则插入新记录

时间:2014-11-12 17:29:33

标签: sql asp.net sql-server

我在按钮单击事件中使用以下代码来更新值。如果该行还不存在,我想在表中插入一个新行。但是当我点击按钮时代码不会执行。这两个存储过程都只是常规的插入和更新SQL语句。

有什么想法?非常感谢你!

SqlConnection con = new SqlConnection(conn.GetConnectionString());                       

SqlCommand cmdnew = new SqlCommand();
cmdnew.CommandType = CommandType.StoredProcedure;
cmdnew.Connection = con;
cmdnew.CommandText = "dbo.UpdateMagtoSpec";

cmdnew.Parameters.AddWithValue("@SpecNo", DropDownList1.SelectedText);
cmdnew.Parameters.AddWithValue("@TestID", ddl_testclass.SelectedValue);
cmdnew.Parameters.AddWithValue("@Max", TextBox6.Text);
cmdnew.Parameters.AddWithValue("@Typical", TextBox8.Text);
cmdnew.Parameters.AddWithValue("@Min", TextBox7.Text);
cmdnew.Parameters.AddWithValue("@Comments", TextArea2.Text);
cmdnew.Parameters.AddWithValue("@Unit", ddl_units.SelectedText);

con.Open();

SqlDataReader rdr = null;
rdr = cmdnew.ExecuteReader();

if (rdr.HasRows)
{
    try
    {
        cmdnew.ExecuteNonQuery();

        Alert.Show("Changes Saved!", MessageBoxIcon.Information);

        btn_edit.Hidden = false;
        Button1.Hidden = true;
        Button2.Hidden = true;

        TextBox6.Readonly = true;
        TextBox7.Readonly = true;
        TextBox8.Readonly = true;
        ddl_units.Readonly = true;
        TextArea2.Readonly = true;
    }
    catch (Exception ex)
    {
        if (ex.Message.ToString().Contains("Error"))
        {
            Alert.Show("Modification Failed!", MessageBoxIcon.Information);
        }
    }                

    con.Close();                
}
else
{                
    SqlCommand cmd = new SqlCommand();

    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Connection = con;
    cmd.CommandText = "dbo.InsertMagtoSpec";

    cmd.Parameters.AddWithValue("@SpecNo", DropDownList1.SelectedText);
    cmd.Parameters.AddWithValue("@TestID", ddl_testclass.SelectedValue);
    cmd.Parameters.AddWithValue("@Max", TextBox6.Text);
    cmd.Parameters.AddWithValue("@Typical", TextBox8.Text);
    cmd.Parameters.AddWithValue("@Min", TextBox7.Text);
    cmd.Parameters.AddWithValue("@Comments", TextArea2.Text);
    cmd.Parameters.AddWithValue("@Unit", ddl_units.SelectedText);

    try
    {
        cmd.ExecuteNonQuery();
        Alert.Show("Records Saved!", MessageBoxIcon.Information);
    }
    catch (Exception ex)
    {
        if (ex.Message.ToString().Contains("Error"))
        {
            Alert.Show("Modification Failed!", MessageBoxIcon.Information);
        }
    }

    con.Close();
}         

1 个答案:

答案 0 :(得分:0)

使用按钮单击声明向我们显示您的aspx代码。很可能你必须将代码连接到事件。

您需要两个部分:

<asp:Button id="Button1"
           Text="Click here for greeting..."
           OnClick="GreetingBtn_Click" 
           runat="server"/>

void GreetingBtn_Click(Object sender,
                           EventArgs e)
    {
        // When the button is clicked,
}