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();;
Related
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.
I have connected my SQL database to my aspx.net form but when I entered the details in the form, it does not seem to update in my SQL Table. I've checked the codes and there doesn't seem to be any errors. Could anyone see what's wrong with my 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.SqlClient;
using System.Data.Sql;
public partial class CustomerLogin : System.Web.UI.Page {
public string sqlTest = "Data Source=TEAFAMILY;Initial Catalog=Bolsen;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e) {
}
static readonly string scriptSuccessNewAccount =
"<script language=\"javascript\">\n" +
"alert (\"Your account has been succesfully created - Thank You!\");\n" +
"</script>";
protected void Button1_Click1(object sender, EventArgs e) {
SqlConnection mDB = new SqlConnection(sqlTest);
mDB.Open();
Type csType = this.GetType();
SqlCommand cmd;
SqlDataReader rdr;
string strSQLSelect = "SELECT cEmail FROM Customers ORDER BY cEmail";
cmd = new SqlCommand(strSQLSelect, mDB);
Console.Write(cmd);
rdr = cmd.ExecuteReader();
//insert new record
string strSQLInsert = "INSERT INTO"
+ " Customers (cFirstname, cLastname, cNumber, cCompanyname, cAdd, cEmail, cPassword)"
+ " VALUES (#FN, #LN, #Num, #Cname, #Add, #Email, #Pw)";
cmd = new SqlCommand(strSQLInsert, mDB);
cmd.Parameters.AddWithValue("#FN", txtFN.Text);
cmd.Parameters.AddWithValue("#LN", txtLN.Text);
cmd.Parameters.AddWithValue("#Num", txtPN.Text);
cmd.Parameters.AddWithValue("#Cname", txtComp.Text);
cmd.Parameters.AddWithValue("#Add", txtCompAdd.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#Pw", txtPW.Text);
cmd.ExecuteNonQuery();
mDB.Close();
ClientScript.RegisterStartupScript(csType, "Success", scriptSuccessNewAccount);
}
}
You are not closing your SqlDataReader. Asides from not calling rdr.Read() and getting any values, you need to call rdr.Close() before executing your second sql statement.
Per MSDN - While the SqlDataReader is being used, the associated SqlConnection is busy serving the SqlDataReader, and no other operations can be performed on the SqlConnection other than closing it. This is the case until the Close method of the SqlDataReader is called. For example, you cannot retrieve output parameters until after you call Close.
The method GetData in the following code works as long as I use valid column names, however, when trying to use a variable (query string parameter value) in the SQL query, I get empty results.
I am assuming I am not using the .AddWithValue method properly. Am I not writing the SQL command properly, or does it have something to do with the code placement of the .AddWithValue method call? Or something else I am missing?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.FriendlyUrls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace Koobek
{
public partial class WebForm6 : System.Web.UI.Page
{
string cat = "";
string getcat = "";
protected void Page_Load(object sender, EventArgs e)
{
var segments = Request.GetFriendlyUrlSegments();
int count = segments.Count;
if (segments.Count > 0)
cat = segments[0];
string getcat = Request.QueryString["cat"];
ListView1.DataSource = this.GetData();
ListView1.DataBind();
System.Diagnostics.Debug.WriteLine(getcat);
}
private DataSet GetData()
{
string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string query = #"SELECT DISTINCT newcatdisplay, newclassdisplay, newclass, newcat FROM ejn_series WHERE newcat = #getcat ORDER BY newclassdisplay";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("#getcat", getcat);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
if (ds.Tables[0].Rows.Count == 0)
{
System.Console.WriteLine("empty");
}
return ds;
}
}
}
}
}
}
You cannot add parameters to a text sql statement. Do this:
string query = #"SELECT DISTINCT newcatdisplay, newclassdisplay,
newclass, newcat FROM ejn_series WHERE newcat = '" + getcat + "' " +
"ORDER BY newclassdisplay";
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;
}
}
}
Following program extracts data from SQL Server 2008 tables, applies a simple for loop and counts total number of records. Program compiles and runs successfully without any error but doesn't print the total count of records to the screen. It doesn't print anything.
.cs (code behind) is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
namespace CountDocs
{
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnCount_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=MEHDI-PC\\SQLEXPRESS; Initial Catalog=PIMS; Integrated Security=true;");
{
using (SqlCommand cmd = new SqlCommand())
{
String sql = "select * from dbo.Company";
cmd.Connection = con;
cmd.CommandText = sql;
con1.Open();
Int32 Total = 0;
Total = (Int32)cmd1.ExecuteScalar();
Console.WriteLine(Total);
if (con.State == ConnectionState.Open)
{
con.Close();
}
for (int i = 0; i < dt.Rows.Count; ++i)
{
string companyname;
companyname = dt.Rows[i].ItemArray[0].ToString();
SqlConnection con1 = new SqlConnection("Data Source=MEHDI-PC\\SQLEXPRESS; Initial Catalog=PIMS; Integrated Security=true;");
{
using (SqlCommand cmd1 = new SqlCommand())
{
String sql1 = "select Count(*) from dbo.Documents where Src=" + "'" + companyname + "'";
cmd1.Connection = con1;
cmd1.CommandText = sql1;
con.Open();
DataTable dt1 = new DataTable();
Int32 Total = 0;
Total = (Int32)cmd1.ExecuteScalar();
Console.WriteLine(Total);
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
}
}
}
}
}
}
Since program is not throwing any syntax error, I guess it could be a logical error. Could someone please notice it for me? Thanks in advance.
The system works correct, because if you write dt1.Rows[0].ToString() you did not get the value of the cell. That is because System.Data.DataRowSystem.Data.DataRowSystem.Data.DataRowSystem.Data.DataRowSystem does not override the method ToString().
I think you have to use dt1.Rows[0].ItemArray[3] or dt1.Rows[0]["column name"].ToString();
Hope this helps.