ASP.net database code using c# - c#

Please tell me the error in this code, the data is not stored in the table.
SqlConnection con;
SqlCommand com;
string constr = #"Data Source=SQL5004.myASP.NET;Initial Catalog=DB_9F2D70_arjunb98;User Id=DB_9F2D70_arjunb98_admin;Password=#;";
protected void submit_Click(object sender, EventArgs e)
{
try
{
con = new SqlConnection(constr);
con.Open();
com = new SqlCommand();
com.CommandText = "insert into table values ('" + DropDownList2.SelectedValue + "', '" + DropDownList1.SelectedValue + "','" + name.Text + "','" + mail.Text + "', '" + Address.Text + "', '" + DropDownList3.SelectedValue + "', '" + ph.Text + "','" + message.Text + "')";
com.Connection = con;
com.ExecuteNonQuery();
}
catch (Exception ex)
{
Page.ClientScript.RegisterStartupScript(
Page.GetType(),
"MessageBox", "<script language='javascript'>alert('Sorry! the data is not Submitted, Please try again ')</script>");
}
finally
{
con.Close();
}

Aahhhhh. You have messed up your code. Also you have not shown your aspx so I am not much aware of the parameters you are using.
Also as suggested by Tim your code is prone to SQL Injection. So its better to used parameterized queries(recommended in your case)
So a simple reference with your code will be as below:-
On ButtonClick you may write something like below
protected void submit_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=SQL5004.myASP.NET;Initial Catalog=DB_9F2D70_arjunb98;User Id=DB_9F2D70_arjunb98_admin;Password=#;"); // connection string described by you
SqlCommand cmd = new SqlCommand("insert into Person(Column1,Column2,Column3,....) values(#Column1, #Column2, #Column3,...)", conn);
cmd.Parameters.AddWithValue("#Column1", TextBoxID.text); // it may be option as per your requirement(ex:- Dropdownlist)
cmd.Parameters.AddWithValue("#Column2", textbox2.Text);
cmd.Parameters.AddWithValue("#Column3", textbox3.Text);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch
{
label.Text = "Error when saving on database";
conn.Close();
}
// Empty your controls here
Control1.text = "";
Control2.text = "";
Control3.text = "";
}
There are also many other links available for your requirement.
http://www.aspsnippets.com/Articles/Using-Parameterized-queries-to-prevent-SQL-Injection-Attacks-in-SQL-Server.aspx
Hope that helps and clarifies your doubt too.
Happy learning :)

Related

How to update datagridview based on its Id?

I'm developing software in which I have a datagridview in wpf in which I have successfully done with inserting the values through fields in datagridview when clicked on insert button. But when I'm clicking on update I'm getting following exception .Find the screenshot of error below:
https://imgur.com/a/CV3n77K
The code that have been tried by myself is below :
public partial class Machine : Window
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\ATS\ATS Data Management System\ATS Data Management System\ATSDataManagementsystemDB.mdf;Integrated Security=True;User Instance=True");
public Machine()
{
InitializeComponent();
MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight;
MaxWidth = SystemParameters.MaximizedPrimaryScreenWidth;
BindMyData();
}
public void BindMyData()
{
try
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM tblmachines", conn);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(comm);
da.Fill(ds);
gridmachine.ItemsSource = ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
conn.Close();
}
}
private void btninsert_Click(object sender, RoutedEventArgs e)
{
try
{
conn.Open();
SqlCommand comm = new SqlCommand("INSERT INTO tblmachines VALUES('" + txtid.Text + "','" + txtsalesdate.Text + "','" + txtname.Text + "','" + txtpartname.Text + "','" + txtprice.Text + "','" + txtquantity.Text + "','" + txttotalamount.Text + "','" + paidpending.Text + "','" + txtpaidamount.Text + "','" + txtpendingamount.Text + "','" + txtcreditamountpaid.Text + "','" + txtpaiddate.Text + "','" + txtpaymentmode.Text + "')", conn);
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
conn.Close();
BindMyData();
}
}
private void btnupdate_Click(object sender, RoutedEventArgs e)
{
try
{
conn.Open();
SqlCommand comm = new SqlCommand("UPDATE tblmachines SET SalesDate='" +txtsalesdate.Text+ "',Name='" +txtname.Text+"',Part Name='"+txtpartname.Text+"',Price="+txtprice.Text+",Quantity="+txtquantity.Text+",Total Amount="+txttotalamount.Text+",PaymentStatus='"+paidpending.Text+"',Paid Amount="+txtpaidamount.Text+",Pending Amount="+txtpendingamount.Text+",Credit Amount Paid="+txtcreditamountpaid.Text+",Paid Date='"+txtpaiddate.Text+"',Payment Mode='"+txtpaymentmode.Text+"'WHERE Id=" + txtid.Text + "", conn);
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
conn.Close();
BindMyData();
}
}
}
}
I want the data to get updated and show up in data grid view but its not happening.
check your Part Name,Paid Amount, Pending Amount and Credit Amount Paid column, i think the error is the column name
SqlCommand comm = new SqlCommand("UPDATE tblmachines SET SalesDate='" +txtsalesdate.Text+ "',Name='" +txtname.Text+"',Part Name='"+txtpartname.Text+"',Price="+txtprice.Text+",Quantity="+txtquantity.Text+",Total Amount="+txttotalamount.Text+",PaymentStatus='"+paidpending.Text+"',Paid Amount="+txtpaidamount.Text+",Pending Amount="+txtpendingamount.Text+",Credit Amount Paid="+txtcreditamountpaid.Text+",Paid Date='"+txtpaiddate.Text+"',Payment Mode='"+txtpaymentmode.Text+"'WHERE Id=" + txtid.Text + "", conn);
You should also add space in the WHERE
Show your table structure

I want to get an alert if email already exits in my database in c# with help of execute scalar method

protected void btnSubmit_Click(object sender, EventArgs e)
{
string db = DropDownList1.SelectedItem.Value + "-" + DropDownList2.SelectedItem.Value + "-" + DropDownList3.SelectedItem.Value;
SqlConnection con = new SqlConnection("data source=BAN095\\SQLEXPRESS; database=Reg-DB; integrated security=SSPI");
SqlCommand cmd = new SqlCommand("select EmailID from Reg where EmailID='" + txtEmail.Text + "'", con);
con.Open();
Int32 count = (Int32)cmd.ExecuteScalar();
if (count==0)
{
Response.Write("email already Exists");
Response.End();
}
else
{
cmd.CommandText = "insert into Reg(FirstName,LastName,EmailID,PhoneNum,Gender,DOB)values('" + txtFirstName.Text + "','" + txtLastName.Text + "','" + txtEmail.Text + "','" + txtMobile.Text + "','" + RdoGender.SelectedItem.Value + "','" + db + "')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
}
Please help me with this. And also for errors like use new keyword to create an object instance that I’m getting.
Put a unique index on EmailID, then perform just the insert and catch for SqlExceptions and check if exception.Number == 2601
Note: Use using statements to ensure that IDisposables will be disposed and use parameterized commands!
protected void btnSubmit_Click(object sender, EventArgs e)
{
string db = DropDownList1.SelectedItem.Value + "-" + DropDownList2.SelectedItem.Value + "-" + DropDownList3.SelectedItem.Value;
using(SqlConnection con = new SqlConnection("data source=BAN095\\SQLEXPRESS; database=Reg-DB; integrated security=SSPI"))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("insert into Reg(FirstName,LastName,EmailID,PhoneNum,Gender,DOB)values(#FirstName,#LastName,#Email,#Mobile,#Gender,#Db)", con))
{
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
//Do the same with other parameters
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
if (ex.Number == 2601) // If instead of unique index, you have a unique constraint/primary key, check for ex.number==2627
{
// Duplicate key! Do whatever you want
}
}
}
}
}

Issue with Insert function in Visual Studio

This is my code:
private void button2_Click(object sender, EventArgs e)
{
try
{
con = new SqlConnection();
con.ConnectionString = constr;
con.Open();
string str1 = "Insert into SuperCars(Car ,mph,price) Values ('" + textBox2.Text + "'," + textBox3.Text + ",'" + textBox4.Text + "' )";
cmd = new SqlCommand(str1, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Inserted successfully.");
con.Close();
}
catch (Exception ex)
{
label5.Text = ex.ToString();
}
}
I want to insert data in my GridView. When I execute this it inserted the data in my database, but it didn't show up in my GridView ... How can I edit it?
You have to reload your GridView by setting its DataSource again.
superCarsGridView.DataSource = null;
superCarsGridView.DataSource = GetSuperCars();
EDIT: testing my code, I had an issue rebinding the list on the DataGridView. I got around this by setting the DataSource to null then again setting to the real DataSource.

Use right syntax error in Mysql

Am not able to fix the error below:
`"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'When,Then) values( '79','WBT-CoE','gyj','yi','yi')' at line 1"` error.
Here's the code:
protected void Button3_Click(object sender, EventArgs e){
string MyconnectionString = "server=localhost;database=requirement_doc;Uid=t;Pwd=123;";
MySqlConnection conn = new MySqlConnection(MyconnectionString);
MySqlCommand cmd;
DataTable dt1 = new DataTable();
cmd = conn.CreateCommand();
cmd.CommandText = "SELECT Req_ID, Actor FROM UseCase where Req_ID='" + txtReqID.Text + "' AND Actor='" + DropDownList1.Text + "'";
MySqlDataAdapter da1 = new MySqlDataAdapter();
da1.SelectCommand = cmd;
da1.Fill(dt1);
if (dt1.Rows.Count > 0)
{
Label1.Text = "Data already exist";
}
else
{
string sql = "INSERT INTO UseCase (Req_ID,Actor,Given,When,Then) values( '" + txtReqID.Text + "','" + DropDownList1.Text + "','" + giventxt.Text + "','" + whentbl.Text + "','" + thentbl.Text + "')";
cmd.Connection = conn;
cmd.CommandText = sql;
conn.Open();
}
try
{
cmd.ExecuteNonQuery();
Label1.Text = " Successfully saved";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
Surround When and then with `` because they are reserved names.
string sql = "INSERT INTO UseCase (Req_ID,Actor,Given,`When`,`Then`) values( '" + txtReqID.Text + "','" + DropDownList1.Text + "','" + giventxt.Text + "','" + whentbl.Text + "','" + thentbl.Text + "')";
When and Then are reserved names in MySQL. So if you use those as column names, you get that error.

Inserting records into a Microsoft Access database in C#

I am inserting data to access 2000-2003 file format database using C#. When I had a database with 2 fields the query works fine, but when there are more fields its is not working.
I have identical code for both and I am not able to find the problem.
using System.Data.OleDb; // By using this namespace I can connect to the Access Database.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private OleDbConnection myconn;
public Form1()
{
InitializeComponent();
myconn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\leelakrishnan\Desktop\NewManageContacts.mdb");
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'newManageContactsDataSet.Contacts' table. You can move, or remove it, as needed.
// this.contactsTableAdapter.Fill(this.newManageContactsDataSet.Contacts);
// TODO: This line of code loads data into the 'newManageContactsDataSet.Contacts' table. You can move, or remove it, as needed.
this.contactsTableAdapter.Fill(this.newManageContactsDataSet.Contacts);
}
private void button1_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
// string query = "insert into Contacts (fname,lname,llnum,mobnum,e-mail,street,city,country) values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "')";
cmd.CommandText = #"insert into Contacts (fname,lname,llnum,mobnum,e-mail,street,city,country) values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "')";
cmd.Connection = myconn;
myconn.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("User Account Succefully Created", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
myconn.Close();
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
textBox7.Text = "";
textBox8.Text = "";
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
This is the code for the table with just 2 fields
public partial class Form1 : Form
{
private OleDbConnection myCon;
public Form1()
{
InitializeComponent();
myCon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\leelakrishnan\Desktop\Database1.mdb");
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.Table1' table. You can move, or remove it, as needed.
this.table1TableAdapter.Fill(this.database1DataSet.Table1);
}
private void button1_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Table1 (name,fname) values ('" + textBox1.Text + "','" + textBox2.Text + "')";
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("User Account Succefully Created", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
myCon.Close();
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
}
}
The extra fields you are trying to insert probably have values that don't readily concatenate into a valid SQL statement. For instance:
string field1 = "meh";
string field2 = "whatever";
string field3 = "'Ahoy!' bellowed the sailor.";
var cmd = new SqlCommand(
"INSERT INTO blah (x, y, z) VALUES ('" + field1 + "', '" + field2 + "', '" + field3 + '")");
Imagine what the concatenated SQL will look like, given the above input.
Worse, imagine the SQL you'll be executing if someone types this into your form:
field3 = "Bobby'); DROP TABLE Users; -- ";
Use parameterised queries via cmd.Parameters.Add or AddRange (described here). The above example might be emended thus:
var cmd = new SqlCommand("INSERT INTO blah (x, y, z) VALUES (#x, #y, #z)");
cmd.Parameters.AddRange(new[] {
new SqlParameter("#x", field1),
new SqlParameter("#y", field2),
new SqlParameter("#z", field2)
});
This code for public:
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\Mohammadhoseyn_mehri\Documents\Data.mdb");
This code for singup button:
try
{
createaccount();
else
{
MessageBox.Show("Please re-enter your password");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
MessageBox.Show("Data saved successfully...!");
con.Close();
}
This is the code for create account method:
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * from Login", con);
con.Open();
String ticketno = textBox2.Text.ToString();
String Purchaseprice = textBox1.Text.ToString();
String my_query = $"INSERT INTO Login (username, pass) VALUES ('{ticketno}', '{Purchaseprice}')";
OleDbCommand cmd = new OleDbCommand(my_query, con);
cmd.ExecuteNonQuery();
If you are working with databases, then mostly take the help of try-catch block statement, which will help and guide you with your code. Here I am showing you that how to insert some values in database with a button click event.
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\pir fahim shah\Documents\TravelAgency.accdb";
try
{
conn.Open();
String ticketno=textBox1.Text.ToString();
String Purchaseprice=textBox2.Text.ToString();
String sellprice=textBox3.Text.ToString();
String my_query = "INSERT INTO Table1(TicketNo,Sellprice,Purchaseprice)VALUES('"+ticketno+"','"+sellprice+"','"+Purchaseprice+"')";
OleDbCommand cmd = new OleDbCommand(my_query, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfuly...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to"+ex.Message);
}
finally
{
conn.Close();
}
private void btnSave_Click(object sender, EventArgs e)**
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"insert into Personal (P_name, P_add,P_Phone)VALUES('" + txtName.Text + "','" +txtAddress.Text + "','" + txtPhone.Text + "')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("Recrod Succefully Created");
con.Close();
txtName.Text = "";
txtAddress.Text = "";
txtPhone.Text = "";
}

Categories