[英]C# SQL Server Update, If not exists, insert new records
I am using the following code in the button click event to update the values. 我在按钮单击事件中使用以下代码来更新值。 If the row does not exist yet, I want to insert a new row into the table.
如果该行尚不存在,我想在表中插入一个新行。 But the code does not execute when I click on the button.
但是,当我单击按钮时,代码不会执行。 Both the stored procedures are just regular insert and update SQL statements.
这两个存储过程都只是常规的插入和更新SQL语句。
Any thoughts? 有什么想法吗? Thank you so much!
非常感谢!
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();
}
Show us your aspx code with the button click declaration. 通过按钮单击声明向我们显示您的aspx代码。 Most probably you have to wire the code to the event.
很可能您必须将代码连接到事件。
You need both parts: 您需要两个部分:
<asp:Button id="Button1"
Text="Click here for greeting..."
OnClick="GreetingBtn_Click"
runat="server"/>
And 和
void GreetingBtn_Click(Object sender,
EventArgs e)
{
// When the button is clicked,
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.