Query Won't Work in ASP.net - c#

I am trying to hide this button if the query result is = to btn1.CommandArgument.
The query works, because I have tested it, but the whole solution is not work.
If I replace
myCommand.ExecuteScalar().ToString()
in the if statement to the query result, the button is hidden.
I have looked several times, but can't find any problems. Thank you.
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
Button btn1 = (Button)e.Item.FindControl("addFollowerButton");
// request Query string
var querystring = Request.QueryString["ProjectId"];
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string select = "Select ProfileId from Project_Follower Where ProjectId = #ProjectId";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(select, myConnection);
myCommand.Parameters.AddWithValue("#ProjectId", querystring);
myCommand.ExecuteScalar();
if (myCommand.ExecuteScalar().ToString() == btn1.CommandArgument.ToString())
{
Button hdn = (Button)e.Item.FindControl("addFollowerButton");
btn1.Visible = false;
}
}
}

You need to execute the .ExecuteScalar() call only once! Grab the result (of type object) and then check to make sure it's not null and if it is, call .ToString() on it and compare to the other string you want to check against:
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(select, myConnection);
myCommand.Parameters.AddWithValue("#ProjectId", querystring);
object result = myCommand.ExecuteScalar();
if (result != null && result.ToString().Equals(btn1.CommandArgument.ToString()))
{
Button hdn = (Button)e.Item.FindControl("addFollowerButton");
btn1.Visible = false;
}
}

Related

ASP.NET Multiple Queries not executing within a loop

I am trying to run multiple queries within a loop. The first query runs ok as I can see it when I step through the code.
However the second query (which is within a loop) is supposed to run depending on the value held from the first. When the loop runs based on that value it seems to be ignoring the query. I put a label to display in place of the query and it displayed so I believe how I have opened/closed my connection is not correct.
c# code:
protected void Page_Load(object sender, EventArgs e)
{
// Get the session of the user
string staffid = Session["StaffId"].ToString();
//Proxy on page load to check IsActive Status
string DefaultConnection = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection myConnection = new SqlConnection(DefaultConnection);
myConnection.Open();
//select the userdetail specific to the logged in user using parameterisation
string query = "SELECT ProxyStatus.ProxyStatusId, ProxyStatus.FunctionId, ProxyStatus.StartDate, ProxyStatus.EndDate, ProxyStatus.IsActive FROM ProxyStatus INNER JOIN Staff ON Staff.StaffId = ProxyStatus.Proxee WHERE (Staff.StaffId = #StaffId)";
DateTime thisDay = DateTime.Today;
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("#staffid", staffid);
SqlDataReader rdr = myCommand.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
Session["StartDate"] = rdr["StartDate"].ToString();
Session["EndDate"] = rdr["EndDate"].ToString();
Session["ProxyStatusId"] = rdr["ProxyStatusId"].ToString();
Session["FunctionId"] = rdr["FunctionId"].ToString();
// Get the session of StartDate and endate, use the session value in a query to compare against the current date
string startdate = Session["StartDate"].ToString();
string enddate = Session["EndDate"].ToString();
string proxystatus = Session["ProxyStatusId"].ToString();
DateTime startdatedata = Convert.ToDateTime(startdate);
DateTime enddatedata = Convert.ToDateTime(enddate);
if (startdatedata > thisDay)
{
string DefaultConnection2 = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection myConnection2 = new SqlConnection(DefaultConnection2);
myConnection2.Open();
string query2 = "UPDATE ProxyStatus SET ProxyStatus.IsActive = 'False' WHERE ProxyStatus.ProxyStatusId = #proxystatus";
myCommand.Parameters.AddWithValue("#newproxystatus", proxystatusnew);
SqlCommand myCommand2 = new SqlCommand(query2, myConnection2);
myCommand2.ExecuteNonQuery();
}
}
}
else
{
rdr.Close();
}
}
}
}
Shouldn't the lines be
SqlCommand myCommand2 = new SqlCommand(query2, myConnection2);
myCommand.ExecuteNonQuery();
be
SqlCommand myCommand2 = new SqlCommand(query2, myConnection2);
myCommand2.ExecuteNonQuery();
instead? The first "myCommand" will still be in use with "rdr".

On Button Click Event my Page is not Redirect to admin.aspx

I Retrive values from admin table and then i store in String variable and finally i compare values my code is not redirect to another page
protected void Button1_Click(object sender, EventArgs e)
{
String uname = (String)txtuser.Text;
String upass = (String)txtp.Text;
String cuser = "";
String cpass = "";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HMSS"].ToString());
conn.Open();
String query = "select username,password from admin where username=#username";
SqlCommand cmd = new SqlCommand(query,conn);
cmd.Parameters.AddWithValue("username", uname);
cmd.Parameters.AddWithValue("password", upass);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
cuser = rdr["username"].ToString();
cpass = rdr["password"].ToString();
}
if (cuser==uname && cpass==upass)
{
Session["user"] = cuser;
Response.Redirect("admin.aspx",true);
}
}
}
Can you check following code lines?
String uname = (String)txtuser.Text;
(string) implicit cast is not necessary: Text property is already a string.
conn.Open();
missing conn.Close(); it's better to add also try/catch
String query = "select username,password from admin where username=#username";
cmd.Parameters.AddWithValue("password", upass);
why don't you check also password in the query?
cuser = rdr["username"].ToString();
It means null value not allowed
if (cuser==uname && cpass==upass)
Problem with case sensitive/trim. In debug do you arrive on Response.Redirect?
Response.Redirect("admin.aspx",true);
Maybe ~/admin.aspx
try to change your condition to below
if (cuser.ToLower() == uname.ToLower() && cpass.ToLower() == upass.ToLower())

How to get text box value in Page_init method in asp.net?

Here is my situation. I want to perform paging, grouping and filtering. So that I am using page_init method. As per my code it's working fine. But user only can give where clause conditions like
For example, I have a textbox in my page. that textbox ID="txtQuery", in that textbox user will enter the where clause like itemID='45366' So i have to make my code like below
cmd.commandText="select * from TABLE_NAME where "+txtQuery.text
So this will show the records. This is the problem now. When I make cmd.commandText like above it throws an error
System.Data.SqlClient.SqlException: Incorrect syntax near 'where'.
If i give directly, It's working fine without any error.
This is my code
string whereQuery = "";
protected void Page_Init(object sender, EventArgs e)
{
// initialize SomeDataTable
if (IsPostBack)
{
string cs = ConfigurationManager.ConnectionStrings["HQMatajerConnectionString"].ConnectionString;
whereQuery = getWhereQuery();
//Response.Write("<br/><br/><br/><br/>" + whereQuery);
using (SqlConnection con = new SqlConnection(cs))
{
string query = #"select transactions.storeid as StoreID, YEAR(transactions.Time) Year, MONTH(transactions.Time) Month,
transactionsEntry.TransactionNumber,transactionsEntry.Quantity,
items.ItemLookupCode,items.DepartmentID,items.CategoryID,items.SubDescription1,
suppliers.SupplierName,suppliers.Code
FROM [HQMatajer].[dbo].[Transaction] as transactions
RIGHT JOIN [HQMatajer].[dbo].[TransactionEntry] as transactionsEntry
ON transactions.TransactionNumber=transactionsEntry.TransactionNumber
INNER JOIN [HQMatajer].[dbo].[Item] as items
ON transactionsEntry.ItemID=items.ID
INNER JOIN [HQMatajer].[dbo].[Supplier] as suppliers
ON items.SupplierID=suppliers.ID
where "+whereQuery; //I tried with txtQuery.text as well it doesn't work
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = query;
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
//SqlDataReader rd = cmd.ExecuteReader();
//ASPxGridView1.Columns.Clear();
ASPxGridView1.AutoGenerateColumns = true;
ASPxGridView1.DataSource = ds;
ASPxGridView1.DataBind();
}
}
}
protected string getWhereQuery()
{
string query = txtQuery.Text;
return query;
}
By default (at first page load) you txtQuery.Text is empty, change your getWhereQuery to:
protected string getWhereQuery()
{
string query = txtQuery.Text;
if(string.IsNullOrEmpty(query))
query=" 1=1";
return query;
}

Return multiple values from sql to label

I have the label:
<asp:Label ID="lbl1" runat="server"></asp:Label>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
lbl1.Text = ImageCheck().ToString();
}
And:
protected int ImageCheck()
{
SqlConnection connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\***.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
string CommandText2 = "SELECT * FROM Machreta WHERE noImage = 1";
SqlCommand command2 = new SqlCommand(CommandText2, connection);
connection.Open();
int check = (int)command2.ExecuteScalar();
connection.Close();
return check;
}
How can i return multiple values? That label display only single value but there are 6 more in the table.
try this:
protected string ImageCheck()
{
var result = new StringBuilder();
using(var connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\***.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"))
{
string CommandText2 = "SELECT * FROM Machreta WHERE noImage = 1";
SqlCommand command2 = new SqlCommand(CommandText2, connection);
connection.Open();
using(var reader = command2.ExecuteReader())
{
while (reader.Read())
{
result.Append(reader.GetString(0));
}
}
return result.ToString();
}
}
of course is only an example and not fully solving your issue but should be a starting point :)
Here is the explanation of ExecuteScalar() method. http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar%28v=vs.71%29.aspx
"Executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored."
Also, SELECT * will fetch all the columns. You probably want to display multiple values for single column. Then select the column name in select statement.
SELECT xyzColumn FROM Machreta WHERE noImage = 1
Lastly, you can assign only one string to label.text. So, you will have to concatenate all these strings (multiple values for single column) and then assign it to label text. Use a reader and ExecuteReader() method instead of ExuecuteScalar().

Update database with values from textbox

i m trying to edit the values in database through textboxes in ASP.
first i retrived the values from database and set those values to the value property of textboxes on the form so that user can see the old values.
now, i want him to enter new values in the same textboxes and when he click on update the new values should be updated in the database.
can any one tell what i have to do to get those new values????
when to submit the form????
the code:
protected void Button2_Click(object sender, EventArgs e)
{
string MachineGroupName = TextBox2.Text;
string MachineGroupDesc = TextBox3.Text;
int TimeAdded = DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
if (MachineGroupName == "" || MachineGroupDesc == "")
{
Label2.Text = ("Please ensure all fields are entered");
Label2.Visible = true;
}
else
{
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =
#"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("UPDATE [MachineGroups] SET ([MachineGroupName]=#MachineGroupName,[MachineGroupDesc]=#MachineGroupDesc,[TimeAdded]=#TimeAdded) WHERE ([MachineGroupID]= #node)");
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
You're not providing the #node parameter. so you should get an exception. Also change your sql statement like that without parenthesis :
long MachineGroupID = Convert.ToInt64(Request.QueryString["node"]);
dataCommand.CommandText = "UPDATE [MachineGroups] SET [MachineGroupName]=#MachineGroupName,[MachineGroupDesc]=#MachineGroupDesc,[TimeAdded]=#TimeAdded WHERE [MachineGroupID]= #MachineGroupID";
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataCommand.Parameters.AddWithValue("#MachineGroupID", MachineGroupID);
EDIT : As you posted your insert page, your table should have an ID column to identify your record uniquely. As I see in your update SQL youe ID column's name is MachineGroupID. So to update your record, you should provide MachineGroupID as #node parameter. try to get this MachineGroupID value in your event and pass it into your Command.
long MachineGroupID = Convert.ToInt64(Request.QueryString["node"]);
dataCommand.CommandText = "UPDATE [MachineGroups] SET
[MachineGroupName]=#MachineGroupName,[MachineGroupDesc]=#MachineGroupDesc,
[TimeAdded]=#TimeAdded WHERE [MachineGroupID]= #MachineGroupID",cn; //add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataCommand.Parameters.AddWithValue("#MachineGroupID", MachineGroupID);
example :
SqlCommand cmdup = new SqlCommand("UPDATE [port1] SET [prt1]=#prt1 WHERE [no]= 1", cn);
cmdup.Parameters.Add("#prt1", TextBox1.Text);
cmdup.ExecuteNonQuery();
I think this may help your case, mention Connection at the last of your update command
ok i have the insert page which is working fine with this code.......
protected void Button2_Click(object sender, EventArgs e)
{
string MachineGroupName = TextBox2.Text;
string MachineGroupDesc = TextBox3.Text;
int TimeAdded = DateTime.Now.Hour+DateTime.Now.Minute+DateTime.Now.Second;
if (MachineGroupName == "" || MachineGroupDesc == "")
{
Label1.Text = ("Please ensure all fields are entered");
Label1.Visible = true;
}
else
{
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =
#"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("INSERT [MachineGroups] ([MachineGroupName],[MachineGroupDesc],[TimeAdded]) VALUES (#MachineGroupName,#MachineGroupDesc,#TimeAdded)");
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}

Categories