error : Cannot find table 0 - asp.net

con.Open();
SqlDataAdapter da4 = new SqlDataAdapter("select * from tblbooking where bookid =(select max(bookid) from tblbooking)", con);
DataSet ds4 = new DataSet();
pay = ds4.Tables[0].Rows[0]["costoftickets"].ToString();
Label4.Text = "Amount to Pay : " + pay + " INR.";
da4.Fill(ds4);
DetailsView1.DataSource = ds4;
DetailsView1.DataBind();
con.Close();

You have not filled the DataSet before accessing its contents, so naturally there's no data in it.
con.Open();
SqlDataAdapter da4 = new SqlDataAdapter("select * from tblbooking where bookid =(select max(bookid) from tblbooking)", con);
DataSet ds4 = new DataSet();
da4.Fill(ds4); // this needs to go before accessing the data
pay = ds4.Tables[0].Rows[0]["costoftickets"].ToString();
Label4.Text = "Amount to Pay : " + pay + " INR.";
DetailsView1.DataSource = ds4;
DetailsView1.DataBind();
con.Close();
Note that you still might get errors if your query returns no data.

Related

Troubles when fetching data from table with a query with a parameter

I'm working with ASP.net. I'm trying to fetch data from a table "Pret" and display them in view. The following code is working properly:
public ActionResult Details(int id)
{
StringBuilder errorMessages = new StringBuilder();
using (SqlConnection con = new SqlConnection(chaineConnexion))
{
DataTable tabRetard = new DataTable();
con.Open();
SqlDataAdapter adp = new SqlDataAdapter();
SqlCommand command = new SqlCommand(
"SELECT Livre.titre,Membre.nom, " +
"FORMAT(Retard.DatePret, 'yyyy-MM-dd') as DatePret, Nbjour FROM Retard " +
"LEFT JOIN Livre ON Retard.Id_livre = Livre.Id " +
"LEFT JOIN Membre ON Retard.Id_membre = Membre.Id", con);
adp.SelectCommand = command;
adp.Fill(tabRetard);
return View(tabRetard);
}
}
Now I'm trying to add a parameter to the query like that, but it throws an exception
System.Data.SqlClient.SqlException : 'Incorrect syntax near 'Retard'
I can't figure out what the problem is !
public ActionResult Details(int id)
{
StringBuilder errorMessages = new StringBuilder();
using (SqlConnection con = new SqlConnection(chaineConnexion))
{
DataTable tabRetard = new DataTable();
con.Open();
SqlDataAdapter adp = new SqlDataAdapter();
SqlCommand command = new SqlCommand(
"SELECT Livre.titre, Membre.nom, " +
"FORMAT(Retard.DatePret, 'yyyy-MM-dd') as DatePret, Nbjour FROM Retard " +
"LEFT JOIN Livre ON Retard.Id_livre = Livre.Id " +
"LEFT JOIN Membre ON Retard.Id_membre = Membre.Id" +
"WHERE Retard.Id_membre = #Id_membre", con);
command.Parameters.AddWithValue("#Id_membre", id);
adp.SelectCommand = command;
adp.Fill(tabRetard);
return View(tabRetard);
}
}
This is caused by a typo in your string concatenation, it's missing whitespace between Membre.Id and WHERE:
SqlCommand command = new SqlCommand(
"SELECT Livre.titre, Membre.nom, " +
"FORMAT(Retard.DatePret, 'yyyy-MM-dd') as DatePret, Nbjour FROM Retard " +
"LEFT JOIN Livre ON Retard.Id_livre = Livre.Id " +
"LEFT JOIN Membre ON Retard.Id_membre = Membre.Id" + /*Needs a space at the end*/
/*or at the beginning*/ "WHERE Retard.Id_membre = #Id_membre", con);
Try this instead:
SqlCommand command = new SqlCommand(
"SELECT Livre.titre, Membre.nom, " +
"FORMAT(Retard.DatePret, 'yyyy-MM-dd') as DatePret, Nbjour FROM Retard " +
"LEFT JOIN Livre ON Retard.Id_livre = Livre.Id " +
"LEFT JOIN Membre ON Retard.Id_membre = Membre.Id " +
"WHERE Retard.Id_membre = #Id_membre", con);
Also, try to avoid use of AddWithValue since it can often cause problems with query parameters such as incorrect type conversion, query plan cache bloat and so on:
command.Parameters.AddWithValue("#Id_membre", id);
Prefer to use SqlCommand's Parameters.Add methods that include the SqlDbType and length parameters, e.g. for int values:
command.Parameters.Add("#Id_membre", SqlDbType.Int).Value = id;
For string values match the length of the related table/view columns, e.g.:
command.Parameters.Add("#nom", SqlDbType.NVarChar, 50).Value = nom;
Interesting reading on AddWithValue:
Can we stop using AddWithValue() already?
AddWithValue is Evil

Hiding duplicate Record from datalist / grid view

i have a data list in which i am displaying record from two different tables like this
string outBox = "Select DISTINCT ToUserID from OutboxMessages WHERE FromUserID = '" + Session["UserId"].ToString() + " ' ";
String inBox = "Select DISTINCT FromUserID from InboxMessages WHERE ToUserID = '" + Session["UserId"].ToString() + " ' ";
con = new SqlConnection("Data Source=(local);Initial Catalog=EventOrganizer;Integrated Security=True");
da = new SqlDataAdapter(outBox, con);
da.Fill(ds1, "Record");
da = new SqlDataAdapter(inBox, con);
da.Fill(ds2, "Record");
ds1.Merge(ds2);
GridView2.DataSource = ds1;
GridView2.DataBind();
DataList1.DataSource = ds1;
DataList1.DataBind();
output is:
FromUserID ToUserID
3
7
2
7
see 7 is appearing twice i want it to appear only once ..any ideas??
Create a new table with the filtered data from Original table and bind that new table to datalist. A sample below
Create a new table first
DataTable dt = new DataTable();
dt.Columns.Add("FromUserID", typeof(string));
dt.Columns.Add("ToUserID", typeof(string));
if(ds1.Tables[0].Rows.Count > 0)
{
foreach(DataRow rw in ds1.Tables[0].Rows)
{
if(rw["FromUserID"] != rw["ToUserID"])
{
dt.Rows.Add(rw["FromUserID"].ToString(), rw["ToUserID"].ToString());
}
else
{
dt.Rows.Add(rw["FromUserID"].ToString(), "");
}
}
}
Bind this newly created table to datalist
DataList1.DataSource = dt;
DataList1.DataBind();

Retrieving multiple rows from stored procedures

My stored procedure proc_search returns only the name on execution and I have been using the following code in ASP.NET to display the value...
SqlCommand cmd = new SqlCommand("proc_search", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#branch", SqlDbType.VarChar).Value = branchidtext.Text;
cmd.Parameters.Add("#Acct", SqlDbType.VarChar).Value = accountidtext.Text;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
nametext.Text = reader[0].ToString();
}
If I have a procedure which returns multiple columns and multiple rows like Name, Address, Age... How do I display it in the text boxes? Please help.
If you know exact order of data you can say
while (reader.Read())
{
nametext.Text = reader[0].ToString();
agetext.Text = reader[1].ToString();
addresstext.Text = reader[2].ToString();
}
etc... If you don't know the ordering than say
while (reader.Read())
{
nametext.Text = reader["Name"].ToString();
agetext.Text = reader["Age"].ToString();
addresstext.Text = reader["Address"].ToString();
}
Use this kind of method. This will retun dataset having multiple rows and cols
public DataSet GetDataSet()
{
SqlConnection conn = new SqlConnection(con);
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "proc_search";
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
DataSet ds = new DataSet();
conn.Open();
da.Fill(ds);
conn.Close();
return ds;
}

Confused about database select query

I am following a session tutorial .The problem is this part.
OleDbCommand fecth = new OleDbCommand(
"SELECT * FROM YONETICI Where YNAME'" +
txtad.Text + "' and YPASS'" + txtpass.Text + "' ",
con);
At this part I am getting an exception named Incorrect syntax -Missing operator(I have tried to translate)
this is the rest of code
OleDbConnection con = new OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+
Server.MapPath("App_Data\\db.accdb"));
con.Open();
OleDbCommand fecth = new OleDbCommand(
"SELECT * FROM YONETICI Where YNAME'" +
txtad.Text + "' and YPASS'" + txtpass.Text + "' ",
con);
OleDbDataReader dr=fecth.ExecuteReader();
if(dr.Read()){
Session.Add("value",txtad.Text);
Response.Redirect("Default.aspx");
You need an equals operator.
OleDbCommand fecth = new OleDbCommand(
"SELECT * FROM YONETICI Where YNAME = '" +
txtad.Text +
"' and YPASS = '" +
txtpass.Text + "' ",
con);
Try that. I added two equals operators to your query.
exactly,you need to add 2 equal sign but i prefer to write your query in a better way
,this one will replace the #Parameter with the value like code below with
fetch.Parameters.addWithValue()
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+Server.MapPath("App_Data\\db.accdb"));
con.Open();
OleDbCommand fecth = new OleDbCommand("SELECT * FROM YONETICI Where YNAME='#txtad' and YPASS='#txtpass'", con);
fecth.Parameters.AddWithValue("#txtad",txtad.Text);
fecth.Parameters.AddWithValue("#txtpass",txtpass.Text);
OleDbDataReader dr=fecth.ExecuteReader();
if(dr.Read()){
Session.Add("value",txtad.Text);
Response.Redirect("Default.aspx");

Populating a drop down list dynamically in ASP.net, and passing that value to another query?

2 questions for everybody.
1) How can I order the years by their value, it crashes when I use DESC?
2) If I populate my list like so:
string strConn = ConfigurationManager.ConnectionStrings["rde_410978ConnectionString"].ToString();
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select Distinct Year from MonthlySales DESC"; //DESC DOESNT WORK?
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddItems.DataSource = objDs.Tables[0];
ddItems.DataTextField = "Year";
ddItems.DataValueField = "Year";
ddItems.DataBind();
ddItems.Items.Insert(0, "Select");
}
How can I make the year selected appear under ddItems.SelectedItem?
WHERE Year = " + ddItems.SelectedItem + "GROUP BY Name ";
That part of another query doesn't work when I populate my list dynamically, any reasons why/ how can I fix it.
Regards.
EDIT:
To make my second question clearer, after debugging its always selecting the top item in the drop down list not the actual selected item?
First, in your sql you are missing "order by"...use this
"Select Distinct Year from MonthlySales order by Year DESC"
Second, you need to make use of the SelectedValue property to get your dropdown's selected value...as below...
WHERE Year = " + ddItems.SelectedValue + " GROUP BY Name";
Having said that, I strongly recommend you to use..."parameterized" sql...Here is an example on how you could enable parameterized sql query...
Give me parameterized SQL, or give me death
Update:
Looks like you are binding your dropdown on every post back...you may try this...
if (!Page.IsPostBack && objDs.Tables[0].Rows.Count > 0)
{
ddItems.DataSource = objDs.Tables[0];
ddItems.DataTextField = "Year";
ddItems.DataValueField = "Year";
ddItems.DataBind();
ddItems.Items.Insert(0, "Select");
}
Ans 1)
cmd.CommandText = "Select Distinct Year from MonthlySales ORDER BY 1 DESC"
You are missing order by. Here it is.
"Select Distinct Year from MonthlySales order by Year DESC";
For your second part you can do this. Please mind the space in " GROUP BY Name"
WHERE Year = " + ddItems.SelectedItem.Text + " GROUP BY Name ";
using (SqlConnection con = new SqlConnection(strConn))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select Distinct Year from MonthlySales Order By DESC";
using (DataSet objDs = new DataSet())
{
using (SqlDataAdapter dAdapter = new SqlDataAdapter())
{
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddItems.DataSource = objDs.Tables[0];
ddItems.DataTextField = "Year";
ddItems.DataValueField = "Year";
ddItems.DataBind();
ddItems.Items.Insert(0, "Select");
}
}
}
}
}

Resources