I'm trying to query a SQL Server database table based on a user variable (using ASP.NET and C#). I want to be able to pull just the user's unique records from the Waste Application Information table where the Farm Owner name is equal to the variable name (which is a string).
Here's part of my code:
conn.Open();
WasteAppData = "SELECT * FROM [WASTE APPLICATION INFORMATION] WHERE [FARM OWNER] = (user variable) ";
SqlCommand com = new SqlCommand(WasteAppData, conn);
GridView1.DataSource = com.ExecuteReader();
GridView1.DataBind();
If I replace the "(user variable)" with the actual value in the table column it does work correctly. Like this: 'Joe Smith' I've tried referencing the variable which is pulled from another webform with no luck... I think my syntax is incorrect? Any help would be great!
You need to do it this way:
WasteAppData = "SELECT * FROM [WASTE APPLICATION INFORMATION] WHERE [FARM OWNER] = #FarmOwn";
using (SqlCommand cmdSQL = new SqlCommand(WasteAppData , conn)
{
cmdSQL.Parameters.Add("#FarmOwn", SqlDbType.NVarChar).Value = strFarmOwnwer;
cmdSQL.Connection.Open();
GridView1.DataSource = cmdSQL.ExecuteReader;
GridView1.DataBind();
}
In this case "strFarmOwner" would be replaced with your actual variable that holds the value you want.
Related
I have a table Registration with many columns. I need to get customer_id and put that value into a variable for use that in a session for moving & use between ASP Webforms. How can I do this?
You can use ExecuteScalar method to get single column value. Below is a very basic example of how to get single column value.
string connectionString = ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("select Customer_id from Registration", con);
con.Open();
string id = cmd.ExecuteScalar().ToString();
}
Here is how you can store the value in session
Session["CustomerID"] = id;
And here is how you can retrieve the value on second page
int ID = 0;
int.TryParse((string)Session["CustomerID"], out ID);
I would like to know how to load data from a database into a asp.net form.
So I use code to get the data via a query "Select * From ... Where ... = ..."
Then I load it into a reader and
While (reader.read)
{ string sProductName = Convert.ToString(reader[1]);
/*
Now I need to display this name and all the other data
(selling price, etc) on the form
But as I do not know how many products there will be it (the form) has to change
as the database information does (more products get added or removed).
*/
}
I do not know how to do that last part. How to make the data found display on screen.
Thanks !
The data I need to display is a the Product Name, the Product Description and the Product Selling Price underneath headings with those names thats all.
For SQL Database,
Take gridview control with id="gridview1" (whatever you like but use same id in code)
SqlConnection sql= new SqlConnection("your data base connection");
SqlCommand cmd = new SqlCommand("select * from your_table_name", sql);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gridview1.DataSource = ds;
gridview1.DataBind();
SqlConnection sql= new SqlConnection("your data base connection");
SqlCommand cmd = new SqlCommand("select * from your_table_name", sql);
sql.open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Textbox1.Text=dr[0].ToString();
Textbox2.Text=dr[1].ToString();
Textbox3.Text=dr[2].ToString();
......................;
}
con.close();
NOTE:
While working with datareader sql connection must be open.
I use textboxes to show the values.You can use where ever it is necessary .dr[0].ToString(),.dr[1].ToString() .....Contains the values of database table
What I am missing to get data from temporary table. This is showing error like Invalid object name #emp. Please help me
I am using Asp.net.
Dim sqlcmd = New SqlCommand("select * into #emp from employees", conn)
sqlcmd.ExecuteNonQuery()
sqlcmd = New SqlCommand("select * from #emp", conn)
Dim dr As SqlDataReader = sqlcmd.ExecuteReader
See Above query is working fine and data is going into temporary table. but it is not selecting again through second one query.
Thanks
Try to use Global Temporary table instead of Local Temporary tabel like.. ##emp
or
You can just use a stored procedure which has all the SQL statement you want to execute and return your desired recordset.
I have a grid view which uses SQL to calculate information that I need! I want to put this calculated total into another table in database.
SELECT StaffDetails.StaffID, SUM(HolidayRequests.RequestTotalDays) AS Expr1
FROM HolidayRequests INNER JOIN StaffDetails ON HolidayRequests.Username = StaffDetails.UserName
WHERE (StaffDetails.StaffID = #staffID)
GROUP BY StaffDetails.StaffID, HolidayRequests.ApprovalStatus
HAVING (HolidayRequests.ApprovalStatus = N'approved')
It basically calculates the total number of approved holiday requests for a staff member which is correct. I want this number to then update the HolidayTaken field in another table each time a holiday is approved.
I have tried an update however you cannot use an aggregate in an update as I have found...Any idea how else I can do this..
you could load the executed Query into a "DataReader" or "DataSet" and from there load the information to the new Table.
you could do:
SqlConnection conn = "You connection";
SqlCommand cmd = new SqlCommand(conn);
cmd.CommandText = "YOUR QUERY";
SqlDataReader rdr = cmd.ExecuteReader();
String UpdateQuery;
while (rdr.Read())
{
UpdateQuery = "UPDATE table set col1=#Expr1 WHERE condition"
cmd.Parameters.AddWithValue("#Expr1", rdr["Expr1"].ToString());
//run update query
cmd.CommandText = UpdateQuery;
cmd.ExecuteNonQuery();
return;
}
cmd.Connection.Close();
Try this
UPDATE StaffDetails a
SET a.HolidayTaken = (SELECT SUM(HolidayRequests.RequestTotalDays)
FROM HolidayRequests INNER JOIN StaffDetails b ON HolidayRequests.Username = b.UserName
WHERE (b.StaffID = #staffID)
GROUP BY b.StaffID, HolidayRequests.ApprovalStatus
HAVING (HolidayRequests.ApprovalStatus = N'approved'))
WHERE a.StaffID = #staffID
Trying to do a recordset, I just want one column of data, but this code is giving me an error.. I'm an ASP.NET newb, can anyone help?:
System.Data.SqlClient.SqlException: Invalid column name
'CustomerName'.
using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
{
con.Open();
using (IDataReader dr = DB.GetRS("select CustomerName from Customer where CustomerID=" + Customer.CustomerID, con))
{
string CustomerName = "CustomerName";
}
}
String EncCustomerName = Encrypt(CustomerName.Replace(".", "").Replace("-", ""),"1");
Question #2: How do I bind the database content to the CustomerName string? It seems like its only returning "CustomerName" as the value for CustomerName string.. I would like it to return the database data for CustomerName string.. Help?
Suggested to use a ExecuteScalar, so i modified the request to this
using (var con = new SqlConnection(DB.GetDBConn()))
using (var cmdContrib = new SqlCommand("SELECT CustomerName FROM Customer WHERE CustomerID=" + ThisCustomer.CustomerID, con))
{
con.Open();
string CustomerName = cmdContrib.ExecuteScalar();
}
And i Get this error:
"string CustomerName = cmdCust.ExecuteScalar();"
CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)
To answer your second question:
// Set it here so you can access it outside the scope of the using statement
string CustomerName = "";
using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
{
con.Open();
using (IDataReader dr = DB.GetRS("select CustomerName from Customer where CustomerID=" + Customer.CustomerID, con))
{
while (dr.Read())
CustomerName = dr["CustomerName"].ToString();
}
}
}
If you're sure you'll only get one CustomerName result, using a DataReader is a bit of an overkill.
SqlCommand.ExecuteScalar Example
string CustomerName = "";
using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
{
SqlCommand cmd = new SqlCommand("SELECT CustomerName FROM Customer WHERE CustomerID = " + Customer.CustomerID, con);
cmd.CommandType = CommandType.Text;
con.Open();
CustomerName = Convert.ToString(cmd.ExecuteScalar());
}
SqlCommand.ExecuteScalar Method
Additional Info
ExecuteScalar returns an object, so you'll need to convert the returned value to the proper type (in this case, string).
Also, you should declare your CustomerName value outside of the using blocks (as I did in my example) - otherwise it will be scoped to the using blocks and not available outside of them.
It means that either CustomerName or CustomerID is not a valid column within your database. Check your table again.
Make sure you are trying to connect correct database.
See CustomerName column should be in Customer table. check spelling also
First, debug and check the value of:
DB.GetDBConn()
You will verify that you are going to the same in Studio as you are in the program.
I think it is the spelling somewhere between the db and your code.
Once you get past the error, you need to fix this:
{
string CustomerName = "CustomerName";
}
You are not accessing the reader, try some kind of tutorial for that stuff.
Try doing a select * from customer where ... and put a breakpoint on your using datareader statement. Then use quick-watch on the datareader object to investigate the columns exposed in the recordset.
Or you could run the select statement on your db of choice to ensure that the column name is the same.
I agree with Madhur above, your column name is not spelled correctly. Or you are not connecting to the correct db.
Hope this helps