passing a parameter to GridView when calling data from database - c#

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 ?

Related

Double data in database

[WebMethod]
public string Login(string Username, string Password)
{
String result;
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Nicole Wong\Desktop\Inari Tracking System\Inari Tracking System\App_Data\Database1.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT Username, Password from UserData where Username = #Username AND Password = #Password", con);
cmd.Parameters.AddWithValue("#UserName", Username);
cmd.Parameters.AddWithValue("#Password", Password);
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
// Create an instance of DataSet.
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count> 0)
{
DateTime dt = DateTime.Now;
SqlCommand cmd1 = new SqlCommand("INSERT INTO ActivityLog (CreateOn, CreateBy) VALUES (#CreateOn,#CreateBy)", con);
cmd1.Parameters.AddWithValue("#CreateOn", dt);
cmd1.Parameters.AddWithValue("#CreateBy", Username);
cmd1.ExecuteNonQuery();
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
// Create an instance of DataSet.
DataSet ds1 = new DataSet();
da1.Fill(ds);
con.Close();
result = "Successful";
return result;
}
else
{
result = "Fail";
return result;
}
This is my simple web method to store user login time into database.
The problem is the data saved twice into the database. For example, I login into the system, then it returns successful, but I checked the database there is two same records saved with the same data. I run with breakpoint but the there is no any duplication, the code run nicely line by line.
Any idea? Thank you in advance
public string Login(string Username, string Password)
{
String result;
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Nicole Wong\Desktop\Inari Tracking System\Inari Tracking System\App_Data\Database1.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT Username, Password from UserData where Username = #Username AND Password = #Password", con);
cmd.Parameters.AddWithValue("#UserName", Username);
cmd.Parameters.AddWithValue("#Password", Password);
//This us pretty much useless on a select, SELECT is a query, not a NonQuery
//cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
// Create an instance of DataSet.
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count> 0)
{
DateTime dt = DateTime.Now;
SqlCommand cmd1 = new SqlCommand("INSERT INTO ActivityLog (CreateOn, CreateBy) VALUES (#CreateOn,#CreateBy)", con);
cmd1.Parameters.AddWithValue("#CreateOn", dt);
cmd1.Parameters.AddWithValue("#CreateBy", Username);
cmd1.ExecuteNonQuery();
//Don't use the DataAdapter and try to fill a dataset from an insert, all this insert will return is ##ROWCOUNT
//SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
// Create an instance of DataSet.
//DataSet ds1 = new DataSet();
//da1.Fill(ds);
con.Close();
result = "Successful";
return result;
}
else
{
result = "Fail";
return result;
}
You executed both your select and your insert twice, with the select it didn't matter so much, but with the insert it does. Remove the .ExecuteNonQuery() from the select and remove the SqlDataAdapter from the insert.

How to Convert DataSet to User Object in C#?

// GetUserByUsername
public DataSet GetUserByUsername(string Username)
{
User _user = null;
using (SqlCommand cmd = new SqlCommand(DBHelper.UserMethod("GetUsername"),con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#username", Username);
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.Fill(ds);
}
return ds;
}
In my above method return type is DataSet, here my dout is if I change the DataType to User then how to Convert that DataSet ds to User let me show you.
For example:
// GetUserByUsername
public User GetUserByUsername(string Username)
{
User _user = null;
using (SqlCommand cmd = new SqlCommand(DBHelper.UserMethod("GetUsername"),con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#username", Username);
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.Fill(ds);
}
return (User)ds;
}
Can I use in this way or is their any other way can I use instead of DataSet, DataTable?
If you don't want to build the User obj by parsing the results yourself go for the automapper lib OR there is a such a thing as strongly type datasets (IE define a set AS User). Its been a long time since I've done that but this will get you started
https://msdn.microsoft.com/en-us/library/esbykkzb(v=vs.110).aspx

Best way to debug parameterized query in c# [duplicate]

This question already has answers here:
Get the generated SQL statement from a SqlCommand object?
(25 answers)
Closed 6 years ago.
Escape ( ' ) symbol in Textbox for asp.net c#
Based on the question in post above, most people suggested that "parameterized query" is the best solution to avoid the sql injection.
Below is my code by using the sql injection
public DataSet checkemp(string user)
{
strsql = "SELECT * from employee where employeeid = #userid";
SqlConnection con = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter(strsql, connectionString);
da.SelectCommand.Parameters.Add("#userid", SqlDbType.VarChar, 50).Value = user;
// pretend the user name is "Micheal"
con.Open();
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
con.Dispose();
return ds;
}
During the debugging, I can only get the query "SELECT * from employee where employeeid = #userid" if I point on "strsql" label, but not "SELECT * from employee where employeeid = 'Micheal'.
Any solution suggested to solve this question and make it most efficiency? thanks everyone!
I would introduce an extension method (although this is not must, actual logic is more important) that returns the parsed query as below, and call that only during debug mode:
public void TestMethod()
{
string cmdStr = "<some sql command text>";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(cmdStr, con);
cmd.Parameters.AddWithValue("<param1>", <value1>); // add parameter in any way you want
#if DEBUG
string parsedQuery = cmd.GetParsedQuery();
Console.WriteLine(parsedQuery); // or whatever
#endif
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
con.Dispose();
return ds;
}
public static string GetParsedQuery(this SqlCommand cmd)
{
if(cmd.CommandType == CommandType.Text)
{
string parsedQuery = cmd.CommandText;
foreach(var p in cmd.Parameters)
{
parsedQuery = parsedQuery.Replace(p.ParameterName, Convert.ToString(p.Value));
}
return parsedQuery;
}
return null;
}
Note that, although I have directly written extension method (for brevity), it should really be defined in a separate static class.
Try MiniProfiler :
"An ADO.NET profiler, capable of profiling calls on raw ADO.NET"
http://miniprofiler.com/
public DataSet checkemp(string user)
{
strsql = "SELECT * from employee where employeeid = #userid";
SqlConnection con = GetOpenConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter(strsql, connectionString);
da.SelectCommand.Parameters.Add("#userid", SqlDbType.VarChar, 50).Value = user;
// pretend the user name is "Micheal"
con.Open();
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
con.Dispose();
return ds;
}
public static DbConnection GetOpenConnection(string connectionString)
{
var cnn = new SqlConnection(connectionString);
// wrap the connection with a profiling connection that tracks timings
return new StackExchange.Profiling.Data.ProfiledDbConnection(cnn, MiniProfiler.Current);
}
** You might need to wrap SqlCommand with ProfiledDbCommand

SQL Datareader failed to bind data to GridView

protected void Button1_Click(object sender, EventArgs e)
{
string query = "select * from aspnet_Users where userName like '%#UserName%'";
connection.Open();
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.Add("#UserName", SqlDbType.NVarChar).Value = TextBox1.Text;
SqlDataReader reader = command.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
connection.Close();
}
I am trying to use connected model to search a user's data in a table but the GridView is always, never fills with data.
You parameter is acting as a string in your query because of single quotes you have include around the parameter. That is the reason it is not able to identify the parameter. Try this:-
string query = "select * from aspnet_Users where userName LIKE #UserName";
Then add it as parameter like this:-
command.Parameters.Add("#MyName",SqlDBType.NVarChar,40).Value ="%" + TextBox1.Text + "%";
You can populate gridview using SqlDataAdapter, your code look like this
string query = "select * from aspnet_Users where userName like '%#UserName%'";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#UserName", TextBox1.Text);
cmd.Connection = conn;
SqlDataAdapter dap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dap.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();

Error when Using queryString

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"];

Categories

Resources