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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With