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);
}
Related
I'm having a bit of a problem when trying to populate cascading comboboxes. First part works great, the first combobox gets filled.
Here is the code:
private void LoadCombo()
{
try
{
SqlConnection conn = new SqlConnection(#"Data source=SERVER\SOURCE;Initial Catalog=MyDatabase; Integrated security=true;");
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select name from sys.tables where type = 'U'", conn);
DataTable dt = new DataTable();
foreach (DataRow row in dt.Rows)
{
comboBox1.Items.Add(row["name"].ToString());
}
}
catch (Exception ex)
{
throw ex;
}
}
Now, all table names are loaded in comboBox1. Now, here's the main problem: I'm trying to retrieve table name from comboBox1 and use the text to pass another query to SQL Server, so that, when I make a selection in comboBox 1, comboBox 2 gets filled with table properties of a specified column of a called table.
Here is the code:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(#"Data source=SERVER\SOURCE;Initial Catalog=MyDatabase; Integrated security=true;");
SqlDataAdapter da = new SqlDataAdapter("select distinct ColumnName from'" + comboBox1.Text + "'", conn);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
comboBox2.Items.Add(row["ColumnName"].ToString());
}
}
catch (Exception ex)
{
throw ex;
}
}
I've been getting an error
Syntax error near columnName
How do I fix this problem? Thank you!
I'm creating a search engine based on SQL database.
Is it possible to get sql data on a List and then show data on labels?
This is my code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=SHKELQIM\SQLEXPRESS;Initial Catalog=Dictionary;Integrated Security=True");
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT Word FROM Dictionary WHERE Word like'%" + lblsearch.Text + "%'", con);
DataSet ds = new DataSet();
da.Fill(ds, "Dictionary");
List<string> word = new List<string>();
foreach (DataRow row in ds.Tables["Dictionary"].Rows)
{
word.Add(row["Word"].ToString());
}
Label1.Text = word[0].ToString();
}
catch (SqlException ex)
{
Label1.Text = ex.Message;
}
finally
{
con.Close();
}
}
}
}
I get an ArgumentOutOfRangeException at line - Label1.Text = word[0].ToString();
I don't know why, because that column contains data.
Also how can I position labels where I want, if I need to create new labels for every word?
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);
}
}
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,
}
I have a database in which a table has name Registration which is used to register the user.
It has only two column one is Username and one is password.
A page named Register.aspx is used for registering the member which have two textbox one is for taking Username(textbox1) and one is for taking password(textbox2) and one button for insert these value in database.
The Main problem is that we cannot write statement like this :
Insert into Registration (Username, password)
values ('TextBox1.text','TextBox2.text')
I am using ADO.net Connection oriented mode, I googled but I didn't find any way to insert row in SQL database in connected mode. Please provide me a idea for inserting this row?
ADO.NET has DataReader which supports Connected mode. All else are disconnected.
DataReader is connected architecture since it keeps conneection open untill all records are fetched
If you want to insert in ADO.NET then you should perform the following steps:
private void btnadd_Click(object sender, EventArgs e)
{
try
{
//create object of Connection Class..................
SqlConnection con = new SqlConnection();
// Set Connection String property of Connection object..................
con.ConnectionString = "Data Source=KUSH-PC;Initial Catalog=test;Integrated Security=True";
// Open Connection..................
con.Open();
//Create object of Command Class................
SqlCommand cmd = new SqlCommand();
//set Connection Property of Command object.............
cmd.Connection = con;
//Set Command type of command object
//1.StoredProcedure
//2.TableDirect
//3.Text (By Default)
cmd.CommandType = CommandType.Text;
//Set Command text Property of command object.........
cmd.CommandText = "Insert into Registration (Username, password) values ('#user','#pass')";
//Assign values as `parameter`. It avoids `SQL Injection`
cmd.Parameters.AddWithValue("user", TextBox1.text);
cmd.Parameters.AddWithValue("pass", TextBox2.text);
Execute command by calling following method................
1.ExecuteNonQuery()
This is used for insert,delete,update command...........
2.ExecuteScalar()
This returns a single value .........(used only for select command)
3.ExecuteReader()
Return one or more than one record.
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
try
{
using (var connection = new SqlConnection(yourConnectionString))
{
string queryString = "Select id, name, age from Table where name = #name";
using (var command = new SqlCommand(queryString, Connection))
{
command.Parameters.AddWithValue("#name", name);
Connection.Open();
SqlDataReader dataReader = command.ExecuteReader();
while (dataReader.Read())
{
item = new Item(long.Parse(dataReader[0].ToString()),
dataReader[1].ToString(),
int.Parse(dataReader[2].ToString()));
}
dataReader.Close();
}
}
}
catch (Exception ex)
{
// if exception will happen in constructor of SqlConnection or Command, the // resource can leak but Dispose method will never be called, couse the object was not created yet.
// Trace and handle here
throw;
}
finally
{
}
But ADO.net is useless for enterprice development. You have to have and abstraction from Data Acess Layer and go to entities, not table records
Use the ORM, Luke!
using System.Data.SqlClient;
string cnstr = "server=.;database=dbname;user=username;password=password;";
SqlConnection con = new SqlConnection(cnstr);
SqlCommand cmd = new SqlCommand { Connection = con };
cmd.CommandText = "Insert into Registration (Username, password) values ('#user','#pass')";
cmd.Parameters.AddWithValue("user", TextBox1.text);
cmd.Parameters.AddWithValue("pass", TextBox2.text);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception)
{
//something;
}
finally
{
if (con != null)
con.Close();
}