How to add passed value to database? - c#

I'm practicing on WebApplication in ASP.NET C#
I have created Product Page in that page I have created gridview with data coming from the database also there is the button called Edit in each row. It will take you to Update Page with that row data. and it will put the values in textbox accordingly.
There are text fields and drop box in Update page, but when i make change to data and click on update button, the data doesn't update in database.
Product.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication5.Product
{
public partial class Product1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string pid = GridView1.SelectedRow.Cells[0].Text;
Response.Redirect("UpdateProduct.aspx?Product_ID=" + pid);
}
}
}
UpdateProduct.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Configuration;
namespace WebApplication5.Product
{
public partial class UpdateProduct : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
String myquery = "Select * from Product where pro_id=" + Request.QueryString["Product_ID"];
SqlConnection con = new SqlConnection(mycon);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = myquery;
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
txtpid.Text = ds.Tables[0].Rows[0]["pro_id"].ToString();
txtpname.Text = ds.Tables[0].Rows[0]["pro_name"].ToString();
txtpprice.Text = ds.Tables[0].Rows[0]["pro_price"].ToString();
txtpq.Text = ds.Tables[0].Rows[0]["pro_qty"].ToString();
}
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
con1.Open();
string sql ="UPDATE Product set pro_name='"+txtpname.Text.ToString()+"',cat_name='"+DropDownList1.SelectedValue.ToString()+"',pro_price='"+txtpprice.ToString()+"',pro_qty='"+txtpq.ToString()+"'where pro_id='"+txtpid.Text.ToString()+"'";
SqlCommand cmd1 = new SqlCommand(sql,con1);
cmd1.ExecuteNonQuery();
Response.Write("Updated!");
}
}
}

Please make try catch block with SQLcatch(SqlException ex), and try to use property's. Also you have nice tool in MSSQL, it's called "SQL server profiler".

Check this : pro_qty='"+txtpq.ToString()+"'--give me space---where pro_id
You don't have space between filed and where clause, give one space after pro_qty and where, your query dosen't execute and you don't see error output, because you don't use all tools.

Related

SQL INSERT INTO works without any errors but does not show any data? (C#)

I've been teaching myself SQL for an upcoming school project.
Now, my problem is rather weird, The INSERT INTO command works fine, so do the values and parameters.
However, when i open my table nothing shows up, it either creates an empty row or simply inserts "0".
The connection string is working and the table name is correct, as well as the database itself.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Windows.Forms;
namespace RegistrationForm
{
public partial class Form1 : Form
{
public string username,password,firstName,lastName,birthDate,phoneNumber,email;
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter da;
private void Form1_Load(object sender, EventArgs e)
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox6.Clear();
textBox7.Clear();
}
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con = new SqlConnection(#"Data Source=(LocalDB)\LOCALDBDEMO;Initial Catalog=ATC_DATA;Integrated Security=True");
con.Open();
cmd = new SqlCommand("INSERT TEST (UserName) VALUES (#UserName)", con);
cmd.Parameters.AddWithValue("UserName", textBox1.Text);
username = textBox1.Text;
password = textBox2.Text;
firstName = textBox3.Text;
lastName = textBox4.Text;
phoneNumber = textBox6.Text;
email = textBox7.Text;
cmd.ExecuteNonQuery();
}
}
}
Here's the actual picture of the rows:
The table
NOTE: I am trying to create a sort of Registration form in Windows Forms (C#).
I think you forgot '#' in adding value...try
cmd.Parameters.AddWithValue("#UserName", textBox1.Text);

struggling on getting XML from database to show on the form on a table or grid

I have been truing to retrieve XML data that I have stored in an XML field in sql server and now i need to show information in a webpage/form as to give the user information about the stored report xml data, the following is my attempt and it throws a index 0 exception
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;
using System.Xml.Linq;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
XmlDocument xdoc = new XmlDocument();
SqlConnection cnn = null;
SqlCommand cmd = null;
try
{
cnn = new SqlConnection();
cnn.ConnectionString = "ICDBConnectionString";
cnn.Open();
string selectQry = "WITH XMLNamespaces('TUReport' AS Debtor) SELECT* FROM TUReport WHERE ConsumerID = #ID FOR XML RAW('TUReport');";
cmd = new SqlCommand(selectQry, cnn);
int ID = Convert.ToInt32(txtIDNumber.Text);
cmd.Parameters.AddWithValue("#ID", ID);
DataSet dataset = new DataSet();
//System.IO.StringReader xmlSR = new System.IO.StringReader(cmd)
XmlReader reader = cmd.ExecuteXmlReader();
dataset.ReadXml(reader, XmlReadMode.ReadSchema);
results.DataSource = reader;
results.DataBind();
cnn.Close();
//if (reader.Read())
// xdoc.Load(reader);
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
cnn.Close();
}
}
}
There is a space missing in the SQL between 'Select' and ''. (Select FROM TUReport)

Crystal Report is not loading without error message

I am generating simple Crystal Report in VS-2012 from SQL Server 2014, unfortunately it is not loading/showing content in the browser. Showing no error.
What I did is, added Project, Added crystal report and configured with SQL Server database, drag and drop items, preview in visual studio is show correctly as data is in SQL Server. I haven't added any extra Dataset or DataTables becuase I am gettinf my data directly from SQL server
Here is the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Odbc;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace CrystalReports
{
public partial class ShowReports : System.Web.UI.Page
{
//SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CrystalReportViewer1.Visible = false;
//CrystalReportViewer1.RefreshReport();
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
ReportDocument myReportDocument = new ReportDocument();
string reportPath = Server.MapPath(#"CrystalReport1.rpt");
myReportDocument.Load(reportPath);
string constring = ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
string query = "SELECT * FROM tblCustomer";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd;
adp.Fill(dt);
myReportDocument.SetDataSource(dt);
CrystalReportViewer1.ReportSource = myReportDocument;
CrystalReportViewer1.Visible = true;
}
}
}

SqlException was unhandled by user code error during execution

I am making page to display information from table (Like inbox page of any email website). But I am gettting the following error:
Incorrect syntax near the keyword 'to'.
Below is my C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Inbox : System.Web.UI.Page
{
SqlConnection con = new SqlConnection();
SqlCommand cmmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
con.ConnectionString=#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\Users\user\documents\visual studio 2012\WebSites\Email\App_Data\Database.mdf;Integrated Security=True";
con.Open();
label1.Text = Session["uid"].ToString();
cmmd.CommandText = "select frm from Inbox where to='" + Session["uid2"].ToString() + "'";
cmmd.Connection= con;
SqlDataAdapter daa = new SqlDataAdapter(cmmd);
DataTable dtt = new DataTable();
daa.Fill(dtt);
if(dtt.Rows.Count > 0)
{
label2.Text = dtt.Rows[0][3].ToString();
}
}
}
How to Solve this error?
Use "[to]" instead of just "to". It is problem when you use reserved term for field name.
It should be like this:
cmmd.CommandText = "select [frm] from [Inbox] where [to]='" + Session["uid2"].ToString() + "'";
EDIT:
And yes, for better security and less error-prone code you should use SqlParameter, something like that:
cmmd.CommandText = "select [frm] from [Inbox] where [to]=#SID"
cmmd.Parameters.Add("#SID", SqlDbType.Varchar);
cmmd.Parameters["#SID"].Value = Session["uid"].ToString();;

how to insert data into sql server in asp.net website?

I tried to insert data into sql server from my website build in vs 2008.For that I used button click event .I tried code shown in youtube but the code doesn't work .It shows error in my website.
The code in .aspx.cs file is
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
conn.Open();
}
protected void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into Insert values('"+txtCity.Text+"','"+txtFName.Text+"','"+txtLName.Text+"')",conn);
cmd.ExecuteNonQuery();
conn.Close();
Label1.Visible =true;
Label1.Text = "Your data inserted successfully";
txtCity.Text = "";
txtFName.Text = "";
txtLName.Text = "";
}
}
`
Okay, let's fix this code up just a little. You're getting there:
var cnnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var cmd = "insert into Insert values(#City,#FName,#LName)";
using (SqlConnection cnn = new SqlConnection(cnnString))
{
using (SqlCommand cmd = new SqlCommand(cmd, cnn))
{
cmd.Parameters.AddWithValue("#City",txtCity.Text);
cmd.Parameters.AddWithValue("#FName",txtFName.Text);
cmd.Parameters.AddWithValue("#LName",txtLName.Text);
cnn.Open();
cmd.ExecuteNonQuery();
}
}
A couple things to note about the modified code.
It's leveraging the using statement to ensure that resources are properly disposed.
It's parameterized to ensure that SQL Injection isn't a possibility.
It's not storing a connection object anywhere, get rid of that stored connection.
**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=mrinmoynandy;User ID=**;Password=****");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SumbitBtn_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into streg(Name,Father,Mother,Dob,Sex,Category,Maritial,Vill,Po,Ps,Dist,State,Pin,Country) values (#name,#father,#mother,#dob,#sex,#category,#maritial,#vill,#po,#ps,#dist,#state,#pin,#country)", con);
cmd.Parameters.AddWithValue(#"name", StNumTxt.Text);
cmd.Parameters.AddWithValue(#"father", FatNumTxt.Text);
cmd.Parameters.AddWithValue(#"mother", MotNumTxt.Text);
cmd.Parameters.AddWithValue(#"dob", DobRdp.SelectedDate);
cmd.Parameters.AddWithValue(#"sex", SexDdl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"category", CategoryDdl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"maritial", MaritialRbl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"vill", VillTxt.Text);
cmd.Parameters.AddWithValue(#"po", PoTxt.Text);
cmd.Parameters.AddWithValue(#"ps", PsTxt.Text);
cmd.Parameters.AddWithValue(#"dist", DistDdl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"state", StateTxt.Text);
cmd.Parameters.AddWithValue(#"pin", PinTxt.Text);
cmd.Parameters.AddWithValue(#"country", CountryTxt.Text);
con.Open();
con.Close();
}
}
Thanks
Mrinmoy Nandy
Phone No.: +91 9800451398
**
Creating procedure will avoid sql injection.
SQL
Create procedure insert
(#City,#FirstName,#LastName)
{
insert into tablename (City,FName,LName)
values(#City,#FirstName,#LastName)
}
C#
SqlConnection con=new sqlconnection("give ur connection string here");
sqlcommand cmd=new sqlcommand();
con.open();
cmd=new sqlcommand("insert",con);
cmd.commandtype=commandtype.storedprocedure;
cmd.parameters.addwithvalue("#City",txtCity.text);
cmd.parameters.addwithvalue("#FName",txtFName.text);
cmd.parameters.addwithvalue("#LNAme",txtLName.text);
cmd.ExecuteNonQuery();
con.close();

Categories

Resources