If first query result = second query result - c#

I am trying to use If statement for two query. If query one = query 2
string select = "Select ProfileId from Project_list Where ProjectId = #ProjectId";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(select, myConnection);
myCommand.Parameters.AddWithValue("#ProjectId", querystring);
object Project_listResult = myCommand.ExecuteScalar();
}
string getProfileId = "SELECT ProfileId FROM User_Profile WHERE UserId = (#UserId)";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(getProfileId, myConnection);
myCommand.Parameters.AddWithValue("#UserId", currentUserId);
object User_profileResult= myCommand.ExecuteScalar();
}
if (Project_listResult == User_profileResult)
{
addFollowerButton.Visible = true;
}
This is the code I have so, but is not working.
Error 18 The name 'Project_listResult' does not exist in the current
Error 19 The name 'User_profileResult' does not exist in the current

You have to define both values outside, so that are in scope to use them. Right now you are define both values in using, so those are just under the scope of only under and not available outside that, so you are getting that error.
A simple suggestion is that avoid use of keywords those are part of different language, as you are using select as variable name. This help to increase readability and increase confusion.
Refer
object Project_listResult = null;
object User_profileResult = null;
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(select, myConnection);
myCommand.Parameters.AddWithValue("#ProjectId", querystring);
Project_listResult = myCommand.ExecuteScalar();
}
string getProfileId = "SELECT ProfileId FROM User_Profile WHERE UserId = (#UserId)";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(getProfileId, myConnection);
myCommand.Parameters.AddWithValue("#UserId", currentUserId);
User_profileResult= myCommand.ExecuteScalar();
}
if (Project_listResult.Equals(User_profileResult))
{
addFollowerButton.Visible = true;
}

If I'm understand you you're trying to compare the objects. So you've got to try
if (Project_listResult.Equals(User_profileResult))
addFollowerButton.Visible = true;
http://msdn.microsoft.com/en-us/library/bsc2ak47(v=vs.110).aspx

Related

SQL Query throws error "failed to convert parameter value from a Guid to String'

I'm trying to get the UserName and put it in TempData but I get an error when the code reaches the ExecuteReader() method.
Here's my query code:
var InvoiceId = TempData["newinvoice"];
TempData["invoiceid"] = InvoiceId;
var UserID = TempData["UserID"];
string connection = "Data Source=.;Initial Catalog=project;Integrated Security=true;";
using (SqlConnection sqlconn = new SqlConnection(connection))
{
using (SqlCommand sqlcomm = new SqlCommand("SELECT UserName FROM AspNetUsers WHERE Id = #id"))
{
sqlcomm.Parameters.Add("#id", SqlDbType.VarChar).Value = UserID;
using (SqlDataAdapter sda = new SqlDataAdapter())
{
sqlcomm.Connection = sqlconn;
sqlconn.Open();
sda.SelectCommand = sqlcomm;
SqlDataReader sdr = sqlcomm.ExecuteReader();
while (sdr.Read())
{
TempData["UserId"] = sdr["UserName"];
}
}
}
}
The User Id from TempData["UserID"] is an nvarchar(450) not an integer. I have no clue why that exception is happening - any help?
Note: here's an example from one of my user ids:
'aa776084-053e-452c-8b0d-b445cdbf457d'
It looks like your id is a uniqueidentifier and if so I would recommend changing your database and code to use GUIDs.
However to fix your problem, you should be able to pass in the UserId and call toString() (as the value is most likely an object) e.g:
sqlcomm.Parameters.Add("#id", SqlDbType.NVarChar, UserID.ToString());
If you're only going to return one results, maybe use ExecuteScalar()
using (SqlConnection sqlconn = new SqlConnection(connection))
{
using (SqlCommand sqlcomm = new SqlCommand("SELECT TOP 1 UserName from AspNetUsers where Id=#id", sqlconn)
{
sqlcomm.Parameters.Add("#id", SqlDbType.NVarChar, UserID.ToString());
object result = sqlcomm.ExecuteScalar();
if (result != null)
{
TempData["UserId"] = result.ToString(); // It looks like you're mixing UserId & UserName .
}
}
}

SQL Query from c# class

I'm trying to modify my code by placing the SQL connections and queries into a C# class because currently all my .aspx.cs has connection strings with different types of queries with parameters
Like this:
string CS2 = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con2 = new SqlConnection(CS2))
{
SqlCommand cmd2 = new SqlCommand("SELECT nombre FROM [Portal_B2e].[dbo].[usuarios] WHERE numero_personal = " + lblCedula.Text + "", con2);
con2.Open();
object labels = cmd2.ExecuteScalar();
lblNombre.Text = labels.ToString();
}
As you notice I complete the query with lblCedula.Text so when I try to do this from a C# class it says lblCedula does not exist in this content.
How could I make a reference to the label I have in another page from the class?
This is my code in the C# class
public static List<Perfil> DeletePerfil()
{
List<Perfil> listDelete = new List<Perfil>();
string CS = ConfigurationManager.ConnectionStrings["DBCSATE"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT nombre FROM [Portal_B2e].[dbo].[usuarios] WHERE numero_personal = " + lblCedula.Text + "", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Perfil perfil1 = new Perfil();
perfil1.perfil = Convert.ToInt32(rdr["perfil"]);
perfil1.descripcion = rdr["descripcion"].ToString();
listDelete.Add(perfil1);
}
}
return listDelete;
}
You can hand over the string by a method parameter.
Also please mention the use of the SqlParameter. It will prevent your Query from SQL Injection
public static List<Perfil> DeletePerfil(string numeroPersonal)
{
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT nombre FROM [Portal_B2e].[dbo].[usuarios] WHERE numero_personal = #PersNo", con);
SqlParameter param = new SqlParameter();
param.ParameterName = "#PersNo";
param.Value = numeroPersonal;
cmd.Parameters.Add(param);
...
}
}
Like others have said, pass in lblCedula.Text as a string parameter to your DeletePerfil method:
public static List<Perfil> DeletePerfil(string numeroPersonal)
...
Then your call looks like this:
...
var deletedProfiles = YourClass.DeletePerfil(lblCedula.Text);
...
And like sstan's comment mentioned, make sure you use SQLParameters instead of using string concatenation to avoid a SQL Injection security hole.

Use more than one row in a select statment

I have a select satement in C# and i was wondering if it is possible to use diaplay email and username in two diffrent label.
Below is the query:
SqlDataReader reader;
string sendMessage = "SELECT Email, username FROM aspnet_Membership WHERE UserId = #UserId";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(sendMessage, myConnection);
myCommand.Parameters.AddWithValue("#UserId", newUserId);
ArrayList emailArray = new ArrayList();
label1 = myCommand.ExecuteReader();
label2 = myCommand.ExecuteReader();
}
Thank you
Yes, of course, but you need to call just one time the ExecuteReader and then use the SqlDataReader returned to get the field values of the current record. (Of course the text returned by the reader should be assigned to the Text property of the label, not to the label itself)
string sendMessage = "SELECT Email, username FROM aspnet_Membership WHERE UserId = #UserId";
using (SqlConnection myConnection = new SqlConnection(connectionString))
using (SqlCommand myCommand = new SqlCommand(sendMessage, myConnection))
{
myConnection.Open();
myCommand.Parameters.AddWithValue("#UserId", newUserId);
using(SqlDataReader reader = myCommand.ExecuteReader())
{
while(reader.Read())
{
label1.Text = reader.GetString(reader.GetOrdinal("EMail"));
label2.Text = reader.GetString(reader.GetOrdinal("UserName"));
}
}
}
Also, do not forget to put the disposable objects like the command and the reader inside the appropriate using statement
Just call ExecuteReader once, and call Read method.Then you can get the values using indexer:
reader = myCommand.ExecuteReader();
reader.Read();
label1.Text = reader["Email"].ToString();
label2.Text = reader["username"].ToString();

SQL query data to cshtml

I'm not very good but I'm trying. I think there is something I don't understand somewhere...
I'm trying to get statistique from a DB like how many row got "X". Look simple. I know the SQL statement for it. There is a lot of walkthrough around. But I don't know how to make it appear on a page.
if(!Request.QueryString["RNum"].IsEmpty() ) {
searchTerm = Request.QueryString["RNum"];
selectCommand2 = "SELECT COUNT(NoEmpl) FROM DTool Where NoEmpl = #0";
}
var Count = db.QueryValue(selectCommand2, searchTerm);
With a submit button to send the query how can I make it appear on a page?
just try this
searchTerm = Request.QueryString["RNum"];
string sqlSelect = "SELECT COUNT(NoEmpl) FROM DTool Where NoEmpl= #NoEmpl";
SqlConnection sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);
// Set SqlDbType based on your DB column Data-Type
sqlCommand.Parameters.Add("#NoEmpl", System.Data.SqlDbType.Varcahr);
sqlCommand.Parameters["#NoEmpl"].Value = searchTerm ;
OR
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(
"SELECT COUNT(NoEmpl) FROM DTool Where NoEmpl= #NoEmpl", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("#NoEmpl", searchTerm ));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
//read here
}
}

Query string in SQL command c#

First of all.. excuse me for my bad English , i hope to be understood.
I'm regullar to work with LINQ , the SQL is new for me.
i'm trying to do the next thing: i have the next method on c#:
public string niceMethod()
{
SqlConnection connection = new SqlConnection("Data Source=*******;Integrated Security=False;");
string commandtext = "SELECT bla FROM items WHERE main = 1";
SqlCommand command = new SqlCommand(commandtext, connection);
connection.Open();
string tDate = (string)command.ExecuteScalar();
connection.Close();
return tDate;
}
I have page for example: items.aspx?nID=144
how can i do that the SELECT command will be with querystring and that will take the value
from the "items" table by the id (nID) that show on the address ?
The table have the design for example:id, title, bla, main.
Try something like this:
int nID = int.Parse(Request.QueryString["nID"].ToString());
niceMethod(nID);
public string niceMethod(int nID)
{
using (var conn = new SqlConnection("Data Source=server;Initial Catalog=blah;Integrated Security=False;"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = #"SELECT bla, id, title FROM items WHERE main = #nID";
cmd.Parameters.AddWithValue("#nID", nID);
string tDate = cmd.ExecuteScalar().ToString();
return tDate;
}
}
Try this:
Pay attention to the (Request.QueryString["nID"] ?? "0").ToString() it's really importent so you wont get exception when there is no query.
public string niceMethod()
{
string tDate = "";
string ID = (Request.QueryString["nID"] ?? "0").ToString(); // Get's the nID query, incase there is no query, returns 0.
using (SqlConnection connection = new SqlConnection("Data Source=*******;Integrated Security=False;"))
{
string commandtext = "SELECT bla FROM items WHERE id=#ID"; //#ID Is a parameter
SqlCommand command = new SqlCommand(commandtext, connection);
command.Parameters.AddWithValue("#ID", ID); //Adds the ID we got before to the SQL command
connection.Open();
tDate = (string)command.ExecuteScalar();
} //Connection will automaticly get Closed becuase of "using";
return tDate;
}

Categories

Resources