ASP.NET select * from table and save them in variable - asp.net

I'am new in asp.net. I want to select values from database table.
If it was PHP I would do it like following code.
$query = mysql_query(" SELECT * FROM Table WHERE id = ".$d." ");
while($row = mysql_fetch_array($query))
{
$firstname = $row['firstname'];
$lastname = $row['lastname'];
}
How would I do if it was in asp.net if I use SqlConnection ...and SqlCommand or maybe if there is some beter Connections.... Thank you in advance guys....

//Create a command, using a parameter
var command = new SqlCommand("select firstname, lastname from table where id=#id");
command.Parameters.AddWithValue("id", id);
DataTable dt = new DataTable();
//use a using statement to ensure the connection gets disposed properly
using(var connection = new SqlConnection("connectionstring"))
{
command.Connection = connection;
connection.Open();
//execute the command and load the results in a data table
dt.Load(command.ExecuteReader());
}
//loop through the results of the data table
foreach(var row in dt.Rows)
{
var firstname = row.Field<string>("firstname");
var lastname = row.Field<string>("lastname");
//do something with firstname and lastname
}
This isn't a direct translation since I'm storing the values in a DataTable, but that is usually better than leaving the data connection open.

Related

How to build correct query notification?

could someone please help me, I'm trying to set up alerts with the total amount of records for some tables that I want. In this example, I'm just trying to return COUNT as a result of one of the tables to say how many records don't have schedules for the customer, however with all these exceptions
Creating a Query for Notification
,I couldn't think of a solution for my case.
SELECT COUNT(A.CODREF)QTDEAGENDSEMAGENDA FROM REGISTROS A INNER JOIN ATENDENTES U ON U.CODUSUARIO = A.CODUSUARIO WHERE A.CODUSUARIO = 11 AND A.STATUS IS NULL AND A.CODREF NOT IN ( SELECT CODREF FROM RETORNOS WHERE CODDIALOGO IS NULL AND AGEND_INTERNO IS NULL ) AND DATEDIFF(DAY, A.INICIO, GETDATE())> 11
All the queries I'm going to assemble will look like this in the example. I had thought of creating a view.
Calling my view:
SELECT QTDEAGENDSEMAGENDA FROM ALERTS
then the query would be simple and it would work, but I saw that it is also on the list not to be used.
This is my code and does not work with this query that I set up or with the View
public class NotificationHub : Hub
{
string qtdeAgendSemAgenda = string.Empty;
[HubMethodName("sendNotifications")]
public string SendNotifications()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
string query = #"SELECT COUNT(A.CODREF)QTDEAGENDSEMAGENDA FROM REGISTROS A INNER JOIN ATENDENTES U ON U.CODUSUARIO = A.CODUSUARIO WHERE A.CODUSUARIO = 11 AND A.STATUS IS NULL AND A.CODREF NOT IN ( SELECT CODREF FROM RETORNOS WHERE CODDIALOGO IS NULL AND AGEND_INTERNO IS NULL ) AND DATEDIFF(DAY, A.INICIO, GETDATE())> 11";
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
qtdeAgendSemAgenda = (dt.Rows[0]["QTDEAGENDSEMAGENDA"].ToString());
}
}
}
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
return Tratar.String(context.Clients.All.RecieveNotification(qtdeAgendSemAgenda));
}

binding dropdownlist values to textbox

When the user selects an order ID, the rest of the order information is displayed in label(s). Display the following: employee ID, order date, freight, shipped name, and country. This functionality should be implemented using direct data access programmatically.
Edit: code example and additional explanation.
String CS = onfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionStr‌​ing;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT OrderID FROM Orders", con);
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "OrderID";
DropDownList1.DataValueField = "OrderID";
DropDownList1.DataBind();
Label1.Text = Convert.ToString(DropDownList1.SelectedItem.Text);
}
What I want is the other fields which are there in orders table to be displayed when a value is selected in the dropdownlist.
Can you make datatable from the SQL Query result, and then add items to dropdownlist from ID column. When you then select an item from DDL, you show the info where the row from datatable match the selected orderID.
I can write code if you want it isn't cleared what I'm meaning.
UPDATE: with code
var ds = new DataSet();
using (var conn = new SqlConnection(connection))
{
conn.Open();
var command = new SqlCommand("Your SQL Query", conn);
var adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
conn.Close();
} //Now you have a dataset, with one table that matches your query result.
//And now we can use a foreach loop to add every OrderID to dropdownlis
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
DDLname.Items.Add(dr[0].ToString());
}
}
//onSelectedValue event
string orderID = DDLname.Text.toString();
Label1.Text = orderID;
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
if(dr[0].toString().equals(orderID))
{
Label2.text = dr[1].toString();
Label3.text = dr[2].toString();
etc....
}
}
}
As you labelled your question with ASP.Net, I assume that this is part of an ASP.Net Webforms application. This means that the drop down list will be inside a web page in a browser. Not clear to me is whether you want the label to be displayed immediately when the user select the item, or only after a post to the server.
In the first case, you'll need javascript and probably something like Ajax or JSON to get the data you want to display for the selected item. In the second case, you could add an event handler for the SelectedIndex_Changed Event of your drop down list. This handler should do something like this:
string CS = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT OrderID FROM Orders WHERE OrderId = #OrderId", con);
cmd.Parameters.AddWithValue("#OrderId", DropDownList1.SelectedItem.Value);
con.Open();
if (reader.Read())
{
SqlDataReader reader = cmd.ExecuteReader();
Label1.Text = String.Format("Employee ID: {0}, order date: {1}, freight: {2}, shipped name: {3}, and country {4}."
, reader["employeeid"].ToString()
, reader["orderdate"].ToString()
, reader["freight"].ToString()
, reader["shipname"].ToString()
, reader["shipcountry"].ToString());
}
}

Specifying column to dataset

I did not know what exactly to write in the title. If you think its an incorrect title I'll change it.
Heres the problem. I am binding a dropdownlist to a dataset (a table) from where I need fields like Name, AddressLine1, AddressLine2, City, Email, Country, etc... And I want to display these fields (values) on labels. Heres the complete code:
public String GetSessionObject()
{
string strSession = "";
if (HttpContext.Current.Session["SessionEmail"] != null)
{
strSession = HttpContext.Current.Session["SessionEmail"].ToString();
}
return strSession;
}
public DataSet BindDropDownListToAUserAddress()
{
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
con.Open();
string strQuery = "SELECT *, FirstName +' '+ LastName as FullName from AUserAddress where AUser_ID = (Select ID from AUser where Email='" + GetSessionObject() + "')";
SqlCommand cmd = new SqlCommand(strQuery, con);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
da.Fill(ds, "AUserAddress");
con.Close();
return ds;
}
ddlName.DataSource = objBindDDL.BindDropDownListToAUserAddress().Tables["AUserAddress"];
ddlName.DataTextField = "FullName";
ddlName.DataBind();
lblDisplayAddressLine1.Text = objBindDDL.BindDropDownListToAUserAddress().Tables["AUserAddress"].Columns.("AddressLine1").ToString();-----------????
This is where I am stuck. I need values from specific columns to go on specific labels. What option(s) do I have? Please guide....
What I have understand your problem, for that you can do this
// Get User's Details
DataSet ds=BindDropDownListToAUserAddress();
// Now from this dataset you can get the specific column like this
if(ds!=null && ds.Tables.Count>0)
{
// I am assuming that your table contains single row of specific user
string AddressLine1= ds.Tables[0].Rows[0]["AddressLine1"].ToString();
string AddressLine2= ds.Tables[0].Rows[0]["AddressLine2"].ToString();
}

Execute select query from code behind

How can i execute a SELECT query from my Code Behind file and then iterate through it?
I want to do something like this (just a simple pseudo example):
// SQL Server
var results = executeQuery("SELECT title, name FROM table");
foreach (var row in results)
{
string title = row.title;
string name = row.name;
}
How can i do this within code?
Something like this:
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader["OrderID"], reader["CustomerID"]));
}
}
}
Source: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx
The connectionString will vary depending on the Database product and the authentication mechanism used (Windows Auth, username/password, etc.). The example above assumes you are using SQL Server. For a complete list of different ConnectionStrings, go to http://www.connectionstrings.com/

Reading SQL Server database using datasource

I have created a datasource to connect with SQL Server database. It works fine when I connected it with GridView. I need to read certain item (say FirstName) and store the value to a variable.
How can I use this datasource? Could you give me the statements for that?
Thanks
The SqlDataSource is intended as what the name implies - a data source for data binding. It is not a way to get individual values from a database table.
If you need to read a single value, you should use straight ADO.NET - SqlConnection and SqlCommand - to read that value - something like:
string sqlStmt = "SELECT FirstName FROM dbo.YourTable WHERE ID = #ID";
using(SqlConnection conn = new SqlConnection(your-connection-string-here-))
using(SqlCommand cmd = new SqlCommand(sqlStmt, conn))
{
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = 4044;
conn.Open();
string firstName = cmd.ExecuteScalar().ToString();
conn.Close();
}
The ExecuteScalar call works only if you want to read a single row, single column value - like here. Otherwise you need to use either the SqlDataReader, or use the DataTable and a SqlDataAdapter to fill that data table (if you have multiple rows).
Update: if you want to use a SqlDataAdapter instead - do this:
public DataTable LoadData()
{
DataTable result = new DataTable();
string sqlStmt = "SELECT ID, FirstName, LastName, Country " +
"FROM dbo.YourTable";
using(SqlConnection conn = new SqlConnection(your-connection-string-here-))
using(SqlCommand cmd = new SqlCommand(sqlStmt, conn))
{
SqlDataAdapter dap = new SqlDataAdapter(cmd);
dap.Fill(result);
}
return result;
}
When you call this method, you'll get back a DataTable that contains the columns you've defined in your SQL statement, and all rows from the database table.
DataTable myData = LoadData();
Now, you can iterate over the rows and get the FirstName value for each row:
foreach(DataRow row in myData.Rows)
{
string firstName = row["FirstName"].ToString();
// do whatever you need to do with the first name
}

Resources