C# SQL Server Update, If not exists, insert new records - sql

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.
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. 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,
}

Related

Database is not being updated with Textbox values on button click event

I have an SQL update command for some Textboxes and Comboboxes. However, when the event is fired the database is not getting updated with the Textboxes and I am not getting any exception errors.
The line in particular that I am having an issue with is cmd.Parameters.AddWithValue("#FR_CMMNT", txt_ResolutionNotes.Text);
Here is my code:
private void Button_Click(object sender, RoutedEventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=WINDOWS-B1AT5HC\\SQLEXPRESS;Initial Catalog=CustomerRelations;Integrated Security=True;");
try
{
SqlCommand cmd = new SqlCommand("UPDATE [hb_Disputes] SET FR_DSP_CLSF=#FR_DSP_CLSF, FR_CUST_CNTCT=#FR_CUST_CNTCT, FR_WRK_REQ=#FR_WRK_REQ, FR_OPN_ERR=#FR_OPN_ERR, FR_SO_TP=#FR_SO_TP, FR_SO_DTLS=#FR_SO_DTLS, FR_CMMNT=#FR_CMMNT, FR_SO_DT_WNTD=#FR_SO_DT_WNTD, FINADJ=#FINADJ, SERTYPE=#SERTYPE, CALLRSN=#CALLRSN, SECCAUSE=#SECCAUSE, MTR=#MTR, RPTTYPE=#RPTTYPE, PRMCAUSE=#PRMCAUSE WHERE DSP_ID=#DSP_ID", con);
cmd.Parameters.AddWithValue("#DSP_ID", txt_RowRecrd.Text);
// Second Row
cmd.Parameters.AddWithValue("#FR_DSP_CLSF", cmb_DisputeClassification.SelectedValue);
cmd.Parameters.AddWithValue("#FR_CUST_CNTCT", cmb_CustomerContact.SelectedValue);
cmd.Parameters.AddWithValue("#FR_WRK_REQ", cmb_requestedwork.SelectedValue);
cmd.Parameters.AddWithValue("#FR_OPN_ERR", cmb_OpenInError.SelectedValue);
cmd.Parameters.AddWithValue("#FR_SO_TP", cmb_ServiceOrderType.SelectedValue);
cmd.Parameters.AddWithValue("#FR_SO_DTLS", cmb_ServiceOrderDetails.SelectedValue);
cmd.Parameters.AddWithValue("#FR_CMMNT", txt_ResolutionNotes.Text);
cmd.Parameters.AddWithValue("#FR_SO_DT_WNTD", DatePicker_ScheduledFor.Text);
// Third Row
cmd.Parameters.AddWithValue("#RPTTYPE", cmb_UtilityRptTyp.SelectedValue);
cmd.Parameters.AddWithValue("#FINADJ", cmb_FinancialAdjustment.SelectedValue);
cmd.Parameters.AddWithValue("#SERTYPE", cmb_ServiceTypeAdjustment.SelectedValue);
cmd.Parameters.AddWithValue("#CALLRSN", cmb_InitialCallReason.SelectedValue);
cmd.Parameters.AddWithValue("#PRMCAUSE", cmb_PrimCause.SelectedValue);
cmd.Parameters.AddWithValue("#SECCAUSE", cmb_UnderlyingCause.SelectedValue);
cmd.Parameters.AddWithValue("#MTR", cmb_MeterIssue.SelectedValue);
con.Open();
cmd.ExecuteNonQuery();
cmd.Dispose();
cmd.Dispose();
cmd.Dispose();
MessageBox.Show("Data updated!");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Asp.net sql deleting a row generated by datatable

I want to create a delete button that gets the id next to it
My method to get data is like this a button generates creates the picture
protected void btnSelect_Click(object sender, EventArgs e)
{
try /* Select After Validations*/
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = ConfigurationManager.ConnectionStrings["SHOT"].ToString();
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.Connection = connection;
cmd.CommandText = "Select * from shot_assessment";
cmd.CommandType = CommandType.Text;
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
cmd.Dispose();
connection.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
catch (Exception ex) { }
}
html code as: `
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="delete">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField></Columns></asp:GridView> `

How to get average rating using Ajax Rating Tool

My code
<form id="form1" runat="server">
<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</cc1:ToolkitScriptManager>
<cc1:Rating ID="Rating1" AutoPostBack="true" OnChanged="OnRatingChanged" runat="server"
StarCssClass="Star" WaitingStarCssClass="WaitingStar" EmptyStarCssClass="Star"
FilledStarCssClass="FilledStar">
</cc1:Rating>
<br />
<asp:Label ID="lblRatingStatus" runat="server" Text=""></asp:Label>
</form>
Rating.aspx
public partial class CS : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = this.GetData("SELECT ISNULL(AVG(Rating), 0) AverageRating, COUNT(Rating) RatingCount FROM UserRatings");
Rating1.CurrentRating = Convert.ToInt32(dt.Rows[0]["AverageRating"]);
lblRatingStatus.Text = string.Format("{0} Users have rated. Average Rating {1}", dt.Rows[0]["RatingCount"], dt.Rows[0]["AverageRating"]);
}
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
protected void OnRatingChanged(object sender, RatingEventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO UserRatings VALUES(#Rating)"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Rating", e.Value);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
}
I found this code online.It is not working. I can not find any errors but it is not inserting records.In this output screen is shows 0 users have rated, Average Rating 0 even after you rate it.
I am new to Ajax and asp.net.If you can give any suggestions it would be helpful
THANK YOU.

How do I print SQL query using MessageBox in C#

I am stuck with this problem since yesterday. I have created a button, which when clicked display the results from a SQL Server table. I thought of using MessageBox to print these results or if there is any other way to print results?
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True");
SqlCommand command = new SqlCommand("SELECT * FROM Products", con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
command.ExecuteNonQuery();
con.Close();
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
I have tried different methods but it never worked.. I am really stuck. If you want more details, let me know. Thanks for the help in advance
Add a datagridview control to show multiple rows and try this code and rename it what you want and replace this YourDataGridVeiwName from the name you set for datagridview control and try below code
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True";
string query = "SELECT ProductName FROM Products;";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, con))
{
con.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(command))
{
DataTable dt = new DataTable();
sda.Fill(dt);
YourDataGridVeiwName.DataSource= dt;
}
con.Close();
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
You need to use the SqlDataReader and iterate over the rows returned, extract what you need from each row, and then display that to the enduser.
I modified your code a bit, to make it safer (using blocks!), and I modified the query to return only the product name (assuming you have that) since you cannot really display a whole row in a message box....
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True";
string query = "SELECT ProductName FROM Products;";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, con))
{
con.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string productName = reader.GetFieldValue<string>(0);
MessageBox("Product is: " + productName);
}
reader.Close();
}
con.Close();
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}

The data isn't being loaded into datagrid view. What am i missing?

I think this is one of those times where I'm looking at the code and it all seems fine because my eye's think it will be. I need a fresh set of eyes to look at this code and tell me way it's not loading into the first datagrid view. Thank you for any help your able to provide.
private DataSet DataSetRentals { get; set; }
public DataRelationForm()
{
InitializeComponent();
}
private void DataRelationForm_Load(object sender, EventArgs e)
{
DataSet relationship = new DataSet("relationship");
/////
SqlConnection conn = Database.GetConnection();
SqlDataAdapter adapter = new SqlDataAdapter("Select * From Car", conn);
DataSet DataSetRentals = new DataSet("Relationship");
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Car");
adapter.Fill(DataSetRentals, "Car");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Car");
DataTable Car;
Car = DataSetRentals.Tables["Car"];
foreach (DataRow drCurrent in Car.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
////////////////////////////////////
SqlDataAdapter adapter2 = new SqlDataAdapter("Select * From CarRental", conn);
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Rentals");
adapter.Fill(DataSetRentals, "Rentals");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Rentals");
DataTable CarRental;
CarRental = DataSetRentals.Tables["Rentals"];
foreach (DataRow drCurrent in CarRental.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
/////
SqlDataAdapter adapter3 = new SqlDataAdapter("Select * From Customer", conn);
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Customer");
adapter.Fill(DataSetRentals, "Customer");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Customer");
DataTable Customer;
Customer = DataSetRentals.Tables["Customer"];
foreach (DataRow drCurrent in Customer.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
////////////////////////
DataSetRentals.Tables.Add(Customer);
DataSetRentals.Tables.Add(CarRental);
DataSetRentals.Tables.Add(Car);
DataRelation Step1 = new DataRelation("Customer2CarR",
Customer.Columns["CustomerNo"], CarRental.Columns["CustomerNo"]);
DataSetRentals.Relations.Add(Step1);
DataRelation Step2 = new DataRelation("CarR2Car",
Car.Columns["CarID"], CarRental.Columns["CarID"]);
DataSetRentals.Relations.Add(Step2);
////////////////////////
CustomerGrid.DataSource= DataSetRentals.Tables["Customer"];
CarRGrid.DataSource = DataSetRentals.Tables["CarRental"];
CarGrid.DataSource = DataSetRentals.Tables["Car"];
CustomerGrid.SelectionChanged += new EventHandler(Customer_SelectionChanged);
CarRGrid.SelectionChanged += new EventHandler(CarR_SelectionChanged);
}
private void Customer_SelectionChanged(Object sender, EventArgs e)
{
if (CustomerGrid.SelectedRows.Count > 0)
{
DataRowView selectedRow =
(DataRowView)CustomerGrid.SelectedRows[0].DataBoundItem;
DataSetRentals.Tables["CarRental"].DefaultView.RowFilter =
"CustomerNo = " + selectedRow.Row["CustomerNo"].ToString();
}
else
{
}
}
private void CarR_SelectionChanged(Object sender, EventArgs e)
{
if (CarRGrid.SelectedRows.Count > 0)
{
DataRowView selectedRow =
(DataRowView)CarRGrid.SelectedRows[0].DataBoundItem;
DataSetRentals.Tables["Car"].DefaultView.RowFilter =
"CarID = " + selectedRow.Row["CarID"].ToString();
}
}
And this is the code for the Database.GetConnection() method:
SqlConnectionStringBuilder stringBuilder = new SqlConnectionStringBuilder();
bool OnUni;
OnUni = (System.Environment.UserDomainName == "SOAC") ? true : false;
stringBuilder.DataSource = (OnUni) ? #"SOACSQLSERVER\SHOLESQLBSC" : "(local)";
stringBuilder.InitialCatalog = "CarRental_P117365";
stringBuilder.IntegratedSecurity = true;
return new SqlConnection(stringBuilder.ConnectionString);
It looks like you may have forgotten to call SqlConnection.Open() to actually open the connection. I would also recommend wrapping your connection in a using and explicitly calling SqlConnection.Close() at the end of it, so you don't accidentally leave it open:
using(SqlConnection conn = Database.GetConnection())
{
conn.Open();
/*
rest of code here
*/
conn.Close();
}
For some other good information/examples of properly opening/disposing of SqlConnections, you can also take a look at these SO questions:
Close and Dispose - which to call?
Do I have to Close() a SQLConnection before it gets disposed?
in a "using" block is a SqlConnection closed on return or exception?
youre not binding your data to any datasoruce.
try something like this
using(SqlConnection conn = Database.GetConnection())
try
{
{
------your code here up to DataTable Car-----
DataTable Car;
Car = DataSetRentals.Tables["Car"];
gridview.Datasource = Car;
}
}
catch (SqlException sqlex )
{
string msg = "Fetch Error:";
msg += sqlex.Message;
throw new Exception(msg);
}
Theres no need to open or close the SQL connection as this is done using the using statement at the top where it opens, and when its finishes closes \ disposes of the connection