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
}
Related
I am creating a time in time out program in which when you click at a row in grid view it gets the data of the employee's last name, first name and middle name, then when I click the button, that data will be inserted to an inner joined table which is the time in time out table where the employee is set as Lname + Fname + Mname AS Employee_name
Here is my code - I need help with inserting the grid view data
SqlConnection con = new
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
string command = "INSERT INTO DTR(EmpRegID, CheckIn) VALUES (#EmpRegID, #CheckIn)";
SqlCommand cmd = new SqlCommand(command, con);
cmd.Parameters.AddWithValue("#CheckIn", DateTime.Now.ToString());
try
{
con.Open();
cmd.ExecuteNonQuery();
GridView2.DataBind();
}
finally
{
con.Close();
}
finally i have done it thank you guys for your answers so here is the code
string test1 = test.SelectedRow.Cells[1].Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
string command = "INSERT INTO DTR(RegEmpID, CheckIn) VALUES (#RegEmpID, #CheckIn)";
SqlCommand cmd = new SqlCommand(command, con);
cmd.Parameters.AddWithValue("#RegEmpID", test1);
cmd.Parameters.AddWithValue("#CheckIn", DateTime.Now.ToString());
try
{
con.Open();
cmd.ExecuteNonQuery();
GridView2.DataBind();
}
finally
{
con.Close();
}
i want select from my sql and create a session from one table field
string strquery = "select * from Registration where username=#username ";
SqlConnection connection2 = DBConnection.getConnection();
connection2.Open();
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = connection;
cmd2.CommandText = strquery;
cmd2.Parameters.Add("#username", txt1_username.Text);
SqlDataReader nwReader = cmd2.ExecuteReader();
string cus = "";
if (nwReader.Read())
{
cus = nwReader["customer_id"].ToString();
}
nwReader.Close();
connection.Close();
Session["customer_id_se"] = cus.ToString();
Response.Redirect("Wedding.aspx");
my problem is: i can't use that field and use in session
You are doing few mistakes, let me point them first(obviously it will solve the issue too).
As i mentioned in the comment, "you are creating connection2 and
opening connection using connection.Open(); it should be either
connection2.Open(); or remove connection2 from the block.
The .Parameters.Add() method expect SqlDbType specify them and add its value using the following statement.
cmd2.Parameters.Add("#username",SqlDbType.VarChar).Value = txt1_username.Text;
There may be situations where nwReader will not having any rows(query returns no result). Accessing value from it in such situation will give you exception as "Invalid attempt to read when no data is present", So you need to check for existence of data in the Reader before accessing it.
That is you should use like the following:
SqlDataReader nwReader = cmd2.ExecuteReader();
string customerId = String.Empty;
if (nwReader.HasRows)
{
customerId = nwReader["customer_id"].ToString();
}
4. customerId is already a string so you need not to convert it again using .ToString() before assigning to the session. So the complete scenario can be coded as like the following:
string strquery = "select * from Registration where username=#username";
SqlConnection connection = DBConnection.getConnection();
connection.Open();
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = connection;
cmd2.CommandText = strquery;
cmd2.Parameters.Add("#username", SqlDbType.VarChar).Value = txt1_username.Text;
SqlDataReader nwReader = cmd2.ExecuteReader();
string customerID = "";
if (nwReader.HasRows)
{
customerID = nwReader["customer_id"].ToString();
}
nwReader.Close();
connection.Close();
Session["customer_id_se"] = customerID;
Note :-
If nwReader.HasRows is false means there is no such record for the
specific username, in this case customerID and hence
Session["customer_id_se"] will be blank.
Updates as per HansKesting's comment,
Select * will fetch the entire rows which satisfies the condition in the Where clause. If you requires only a single value and you are sure that the result will be either empty or a single value then you can use SELECT column_name from ... and in such situations use ExecuteScalar to get the value.
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.
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"].ConnectionString;
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());
}
}
Here's my code. I am not able to set TableName variable, it is throwing an exception
Must declare the table variable "#TableName"
public DataTable getAllDataFromTable(String TableName)
{
cmd.CommandText = "select * from #TableName";
cmd.Parameters.AddWithValue("#TableName", TableName);
da.SelectCommand = cmd;
da.Fill(dt);
return dt;
}
You cannot use a parameter in that fashion. The best way to implement what you are looking for is to use a string.Format() method to create your select statement. The only real draw back is the fact you open the method up to SQL Injection.
public DataTable getAllDataFromTable(String TableName)
{
cmd.CommandText = string.Format("select * from {0}", TableName)";
da.SelectCommand = cmd;
da.Fill(dt);
return dt;
}
Here is a similar thread.
Table name and table field on SqlParameter C#?