Error when Using queryString - c#

when I try to get the Url and pass it to procedure
it didn't passed
string ID = Request.QueryString["URL"];
youtube y = new youtube();
y.URL = ID;
repCurrentVideo.DataSource = y.CurrentVideo();
repCurrentVideo.DataBind();
lblDetails.Text = "no details available about this video";
an error shown to me said
Procedure or function 'currentvideo' expects parameter '#URL', which was not supplied.
Exception Details: System.Data.SqlClient.SqlException: Procedure or function 'currentvideo' expects parameter '#URL', which was not supplied.
and this is the stored procedure invoking code
public DataTable CurrentVideo()
{
CreateConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#URL", URL);
SqlDataAdapter da = new SqlDataAdapter("currentvideo", conn);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}

You are never adding the SqlCommand (cmd) to your data adapter
try something like this:
cmd.Parameters.AddWithValue("#URL", URL);
da.SelectCommand = cmd;
or
CreateConnection();
SqlCommand cmd = new SqlCommand("currentvideo", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#URL", URL);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
Also, while we are on the topic of SqlCommands, I believe it is best to wrap them in a using statement as they are of type IDisposable.
using (SqlCommand command = new SqlCommand("currentvideo", conn)) {
...
}
Check out this link to see what it looks like:
http://www.dotnetperls.com/sqlcommand
Edit:
So based on your URL, you are looking for the wrong query string parameter. You need to change the assignment of ID to this:
string ID = Request.QueryString["ID"];

Related

Adding integer parameter to stored procedure in ASP.NET C#

While trying to pass an integer parameter #id to a stored procedure, I get an error da.Fill(ds):
Additional information: Conversion failed when converting the varchar value '#id' to data type int.
I have made sure that integer value is passed and stored procedure contain the correct datatype. What other possibilities are there to rectify this error?
SqlConnection conn = new SqlConnection(cs);
conn.Open();
SqlCommand cmd1 = new SqlCommand("asp_GetTrainingDetail", conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#id", id);
SqlDataAdapter da = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
da.Fill(ds);
If you know better, do not use AddWithValue() ... it has to "guess" what datatype you have in your DB based on what you put into the command. It is errorprone and causes unneeded conversions to take place.
Also: use using(..) around disposables, especially when using Database-access as it will close your connections even if exceptions arise - not using using might let some connection stay unclosed.
DataSet ds = new DataSet ();
using (var conn = new SqlConnection (cs))
{
using (var cmd1 = new SqlCommand ("asp_GetTrainingDetail", conn))
{
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add("#id", System.Data.SqlDbType.BigInt).Value = id;
using (var da = new SqlDataAdapter (cmd1))
{
da.Fill (ds);
}
}
}
Read the link in do not use AddWithValue() for more background infos.
Try this...
SqlConnection conn = new SqlConnection(cs);
conn.Open(); SqlCommand cmd1 = new
SqlCommand("asp_GetTrainingDetail", conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#id", Int.Parse(id));
SqlDataAdapter da = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
da.Fill(ds);

I have to show all the rows in my query - where's my mistake?

public Section SectionView(object id, SqlConnection conn)
{
using (SqlCommand cmd = new SqlCommand())
{
if (conn.State == ConnectionState.Closed)
conn.Open();
SqlDataAdapter sqlda = new SqlDataAdapter("TMR_SECTION_VIEW", conn);
SqlDataAdapter da = new SqlDataAdapter("data", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "TMR_SECTION_VIEW";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#sectionID", id.ToString);
cmd.Parameters.AddWithValue("#name", name);
da.SelectCommand = cmd;
DataTable dt = new DataTable();
DataTable dtbl = new DataTable();
sqlda.Fill(dtbl);
cmd.ExecuteNonQuery();
return id;
}
}
My stored procedure is:
ALTER PROCEDURE [dbo].[TMR_SECTION_VIEW]
#sectionID int, #name varchar(100)
AS
BEGIN
SELECT *
FROM Section
WHERE sectionid = #sectionID
END
You have things a little bit out of order...
You should be specifying the command name on the SqlCommand (not the DataAdapter) and you should be telling the DataAdapter to use the SqlCommand.
I'd change this to allow you to specify the Stored Procedure name as a parameter when you call the function:
public Section SectionView(object id, SqlConnection conn, string sql = String.Empty)
{
if (!String.IsNullOrEmpty(sql))
{
if (conn.State == ConnectionState.Closed) conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#sectionID", id.ToString);
cmd.Parameters.AddWithValue("#name", name);
SqlDataAdapter da = new SqlDataAdapter
{ SelectCommand = cmd };
DataTable dtbl = new DataTable();
sqlda.Fill(dtbl);
return id;
}
}
}
You duplicated a lot of things (like setting the CommandType of your SqlCommand) and you created DataTable dt without using it, so I removed it from the sample in my answer.
So what's happening here is that you're specifying a sql string as a parameter (which can be a normal SQL query or a stored procedure) and you're building a SqlCommand with it that has parameters.
Using that SqlCommand, you're creating a DataAdapter having the SqlCommand as its SelectCommand and then you're using that DataAdapter to fill the DataTable.
NOTE: You don't need to execute SqlCommand.ExecuteNonQuery() when retrieving data as the DataAdapter.Fill() function basically does that for you.
ExecuteNonQuery would be useful when inserting or updating data - not when reading data.

Trying to pass SqlCommand in SqlDataAdapter as parameters

I've successfully built up my method to execute a select command. It is working fine. Then I change my code for SqlDataAdapter DA = new SqlDataAdapter();
I tried to pass SqlCommand as CommandType.Text in the parameters but I can not do it successfully. I get error. Is there any way if I can pass it as parameters. Please see my code.
Running code (aspx page code)
if ((!string.IsNullOrEmpty(user_login.Value)) && (!string.IsNullOrEmpty(user_pass.Value)))
{
// username & password logic
DataTable dt = new DataTable();
string strQuery = "SELECT 1 FROM TBL_USER_INFO WHERE USERNAME = #USERNAME AND PASSWORD = #PASSWORD";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#USERNAME", SqlDbType.VarChar).Value = user_login.Value.Trim();
cmd.Parameters.Add("#PASSWORD", SqlDbType.VarChar).Value = user_pass.Value.Trim();
DBConnection conn_ = new DBConnection();
dt = conn_.SelectData(cmd);
if (conn_.SQL_dt.Rows.Count > 0)
{
Response.Redirect("Home.aspx", false);
}
}
Successful connection class code
public DataTable SelectData(SqlCommand command)
{
try
{
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter();
command.CommandType = CommandType.Text;
command.Connection = conn;
DA.SelectCommand = command;
DA.Fill(SQL_dt);
return SQL_dt;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
How can I pass CommandType.Text as parameters for SqlDataAdapter?
Error code
public DataTable SelectData(SqlCommand command)
{
try
{
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter(command.CommandType.ToString(), conn);
// command.CommandType = CommandType.Text;
// command.Connection = conn;
DA.SelectCommand = command;
DA.Fill(SQL_dt);
return SQL_dt;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
I am getting this error:
System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.
at System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method)...
public DataTable SelectData(string query)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Your Connection String here"))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
adp.Fill(dt);
return dt;
}
}
}
}
To use:
SelectData("select * from yourTable");
Reds has the answer. Just to clean the code up a little bit...
public DataTable SelectData(string query)
{
using (var connection = new SqlConnection("myConnectionString"))
using (var command = new SqlCommand(query, connection))
using (var adapter = new SqlDataAdapter(command))
{
var dt = new DataTable();
connection.Open();
adapter.Fill(dt);
return dt;
}
}
Actually you should pass the connection object on SQLCommand.Hope it helped you
DBConnection conn_ = new DBConnection();
SqlCommand cmd = new SqlCommand(strQuery,conn_);
The error that you are getting is not related to CommandType.Text, it says you have initialised the connection property of of SelectCommand. Basically you should uncomment "command.Connection = conn;" to get rid of this error. If you still face any other issue , it is better to provide those details in the questions to provide accurate answer.

Procedure or function 'UserManagement' expects parameter '#CallType', which was not supplied [duplicate]

This question already has answers here:
Error: Procedure or function expects parameter which was not supplied
(2 answers)
Closed 5 years ago.
String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Add("#CallType", SqlDbType.VarChar).Value = ddlCalltype.SelectedValue.ToString();
cmd.Parameters.Add("#Format", SqlDbType.VarChar).Value = ddlFormat.SelectedValue.ToString();
cmd.Parameters.Add("#disposition", SqlDbType.VarChar).Value = ddlDisp.SelectedValue.ToString();
cmd.Parameters.Add("#SubDisposition", SqlDbType.VarChar).Value = ddlSubdisp.SelectedValue.ToString();
cmd = new SqlCommand("UserManagement", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = cmd;
da.Fill(dt);
gvDetails.DataSource = dt;
gvDetails.DataBind();
gvDetails.Visible = true;
Your code is a big mess. To me it looks like you've just used copy and paste from a bunch of other places and don't quite really understand what's going on in there.
It should be something like this:
String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
DataTable dt = new DataTable();
using(var con = new SqlConnection(strConnString))
{
using(var cmd = new SqlCommand("UserManagement", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#CallType", SqlDbType.VarChar).Value = ddlCalltype.SelectedValue.ToString();
cmd.Parameters.Add("#Format", SqlDbType.VarChar).Value = ddlFormat.SelectedValue.ToString();
cmd.Parameters.Add("#disposition", SqlDbType.VarChar).Value = ddlDisp.SelectedValue.ToString();
cmd.Parameters.Add("#SubDisposition", SqlDbType.VarChar).Value = ddlSubdisp.SelectedValue.ToString();
using(var da = new SqlDataAdapter())
{
da.SelectCommand = cmd;
da.Fill(dt);
}
}
}
gvDetails.DataSource = dt;
gvDetails.DataBind();
gvDetails.Visible = true;
This line assigned new instance of SqlCommand to cmd for second time instead of using existing SqlCommand which contains declared parameters, therefore removing all parameters already declared above:
cmd = new SqlCommand("UserManagement", con);
The correct way to manage SqlCommand with parameterized stored procedure should be like this, with using statement to manage system resources during execution (better to use try...catch...finally block in case you want to handle SqlException):
String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
var dt = new DataTable();
using (var con = new SqlConnection(strConnString))
{
con.Open();
using (var cmd = new SqlCommand("UserManagement", con))
{
cmd.Parameters.Add("#CallType", SqlDbType.VarChar).Value = ddlCalltype.SelectedValue.ToString();
cmd.Parameters.Add("#Format", SqlDbType.VarChar).Value = ddlFormat.SelectedValue.ToString();
cmd.Parameters.Add("#disposition", SqlDbType.VarChar).Value = ddlDisp.SelectedValue.ToString();
cmd.Parameters.Add("#SubDisposition", SqlDbType.VarChar).Value = ddlSubdisp.SelectedValue.ToString();
cmd.CommandType = CommandType.StoredProcedure;
// using SqlDataAdapter
using (var da = new SqlDataAdapter)
{
da.SelectCommand = cmd;
da.Fill(dt);
}
// using DataTable.Load directly
// dt.Load(cmd.ExecuteReader());
}
con.Close();
}
// other stuff
NB: In short you can replace the second assignment of cmd in question using cmd.CommandText = "UserManagement";, hence it just supplying stored procedure name instead assigning another instance of SqlCommand. Also instead of ExecuteNonQuery() try using ExecuteReader() with DataTable.Load() method.

passing a parameter to GridView when calling data from database

so my GridView Returns all the data in my Table but i want to return data that are related to the UserName attribute in the table,mind you that i have Multiple UserName's in the table.
i tried giving my function a string username and in my page_load:
string SessionName;
protected void Page_Load(object sender, EventArgs e)
{
SessionName = Session["Username"].ToString();
DataSet ds = InsertClass.GetCart(SessionName);
}
in my class:
public static DataSet GetCart(string UserName)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ToString());
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM [ShoppingCart] WHERE UserName = #UserName ", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("#UserName", UserName));
DataSet ds = new DataSet();
SqlDataAdapter adapter1 = new SqlDataAdapter(cmd);
adapter1.Fill(ds);
conn.Close();
return ds;
}
Edit:my mistake guys i didnt add the parameter to my function because i was trying alot of things before i asked the question and forgot to put it back.
You are not passing username as string parameter here in your code public static DataSet GetCart()
Here is correct one:
public static DataSet GetCart(string userName)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ToString());
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM [ShoppingCart] WHERE UserName = #UserName ", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#UserName", userName);
DataSet ds = new DataSet();
SqlDataAdapter adapter1 = new SqlDataAdapter(cmd);
adapter1.Fill(ds);
conn.Close();
return ds;
}
So in your page_load you are calling your GetCart function with parameter SessionName, but i cannot see your GetCart function is taking any parameter:
DataSet ds = InsertClass.GetCart(SessionName);
public static DataSet GetCart()
{.....}
And what is the reference of UserName, when you add the parameter to sql query:
cmd.Parameters.Add(new SqlParameter("#UserName", UserName));
Did you debug and see that you are passing the right parameter ?

Categories

Resources