How can I show mutlitple Rows in Visiual Studio 2013 Website project - c#

I'm using C# language and Visual Studio 2013. I'm trying to show multiple rows in my website but it's only showing the first result
I'm trying
String show = "Select Posts from userPosts where Username='John'";
SqlCommand com = new SqlCommand(show, con);
String str = com.ExecuteScalar().ToString();
Response.Write(str);
This is only showing the first result with the user name JOHN but I want them all.

This is because you have used ExecuteScalar() Try it like this (the result is shown in a DataGridView):
String show = "Select Posts from userPosts where Username='John'";
SqlConnection con = new SqlConnection(connStr);
SqlDataAdapter da = new SqlDataAdapter(show,con);
DataSet ds = new DataSet();
da.Fill(ds,"tbl");
dataGridView1.DataSource = ds.Tables[0];
If you don't want to show in DataGridView and just store in a variable use a List<string> like this:
List<string> Posts = new List<string>();
foreach (DataRow item in ds.Tables[0].Rows)
{
Posts.Add(item[0].ToString());
}
Also you can use SqlDataReader as another option.

You are using ExecuteScalar [Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. ]
Try ExecuteReader.
String show = "Select Posts from userPosts where Username='John';
using (SqlCommand command = new SqlCommand(show, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
Console.WriteLine(reader.GetValue(i));
}
Console.WriteLine();
}
}
}
BTW You can try light ORM like Dapper https://github.com/StackExchange/dapper-dot-net. It really nicely remove these horrible while loop

ExecuteScalar()- It executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx.
Instead of ExecuteScalar use ExecuteReader

Related

Need to select a value from table and store it into variable

Hello everyone I am currently working on some testing project and I am having a little problem. Using selenium, I need to SendKey in specific element but instead of fixed value i need to use value (data) from my database. Can anyone help me with how to retrieve single value from database and store it in a variable so i can use it later.
Thank you and sorry for a noobish question - see code below:
SqlConnection conn = new SqlConnection();
SqlCommand command;
SqlDataReader dataReader;
conn.ConnectionString = "Server=******;Database=****;User ID=sqlserver;password=****;MultipleActiveResultSets=true;");
string query = "select RequestID, from AutomaticPayment where RequestID ='1230322'";
DataTable dt = new DataTable();
command = new SqlCommand(query, conn);
conn.Open();
dataReader = command.ExecuteReader();
dt.Load(dataReader);
driver.FindElement(By.Id("requestID")).SendKeys(VALUE FROM DATABASE);
You can use the following code
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlDataAdapter sda = new SqlDataAdapter(query, connection);
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
try
{
result = cmd.ExecuteScalar().ToString();
}
catch(NullReferenceException n)
{
result = "";
}
}
ExecuteScaler gets you the first column of the first row and additional columns are ignored. Use the value from result in your SendKeys()
Use conditions to limit the result:
Select data
SELECT TOP 1 RequestID FROM AutomaticPayment // Always returns 1 row
Or
SELECT RequestID FROM AutomaticPayment WHERE Id = 123 // Id must be unique to return 1 row
And maybe other ways.
Get value
var value = dt.Rows[0][1];
Or
var value = dt.Rows[0]["RequestID"];
From what i worked on with SqlCommand just do the following :
int yourId = 0;
dataReader = command.ExecuteReader()
while(dataReader.Read())
{
yourId = dataReader.GetInt32(0);
}
With that, you should have your value set to the first column of the dataReader. (that is selected thanks to your query, since you are requesting on a specific id, i guess it will return only one column
there is many other type available for Reader : Reader Microsoft Doc
And if you have in the futur many data to collect, use the ORM entity framework, work well for me
Source
EDIT :
Since you are only querying one data, maybe the solution of #work_ishaan is better than mine in this case, check it out.

Why foreach loop does not work with datagridview selected rows in C#?

I am new to c# and using windows forms.
The following code loops through all selected rows in datagridview and take variables from cell0 and 4 as condition to use in sql query.
I multi-select rows then use this code and when I check the result in sql table I find this code only consider the first selected row in datagridview and ignore the rest.
Anyone knows how can I fix it, or what I am doing wrong? please help , thank you
foreach (DataGridViewRow row in DGV.SelectedRows)
{
OrderNumber = Convert.ToInt32(DGV.SelectedRows[0].Cells[0].Value);
OrderDateTime = Convert.ToDateTime(DGV.SelectedRows[0].Cells[4].Value);
MyConnection.Open();
MyCommand.CommandText = "UPDATE List_of_All_Orders set Delivery_State=#_Delivery_State WHERE Order_Number=#_OrderNumber and Date_Time_Ordered =#_OrderDateTime";
MyCommand.Connection = MyConnection;
MyCommand.Parameters.Add("#_Delivery_State", SqlDbType.NVarChar).Value = button7.Text;
MyCommand.Parameters.Add("#_OrderNumber", SqlDbType.Int).Value = OrderNumber;
MyCommand.Parameters.Add("#_OrderDateTime", SqlDbType.DateTime).Value = OrderDateTime;
MyCommand.ExecuteNonQuery();
MyCommand.Parameters.Clear();
MyConnection.Close();
}
I multi-select rows then use this code and when I check the result in
sql table I find this code only consider the first selected row in
datagridview and ignore the rest.
That's too normal because you use same row cell as DGV.SelectedRows[0] in every iteration, not the rows that you iterate.
Change your
OrderNumber = Convert.ToInt32(DGV.SelectedRows[0].Cells[0].Value);
OrderDateTime = Convert.ToDateTime(DGV.SelectedRows[0].Cells[4].Value);
to
OrderNumber = Convert.ToInt32(row.Cells[0].Value);
OrderDateTime = Convert.ToDateTime(row.Cells[4].Value);
Also use using statement to dispose your connection and command automatically instead of calling Close or Dispose methods manually.
using(var MyConnection = new MySqlConnection(conString))
using(var MyCommand = MyConnection.CreateCommand())
{
MyCommand.CommandText = "UPDATE List_of_All_Orders set Delivery_State=#_Delivery_State WHERE Order_Number=#_OrderNumber and Date_Time_Ordered =#_OrderDateTime";
MyConnection.Open();
foreach (DataGridViewRow row in DGV.SelectedRows)
{
MyCommand.Parameters.Clear();
OrderNumber = Convert.ToInt32(row.Cells[0].Value);
OrderDateTime = Convert.ToDateTime(row.Cells[4].Value);
MyCommand.Parameters.AddWithValue("#_Delivery_State", button7.Text);
MyCommand.Parameters.AddWithValue("#_OrderNumber", OrderNumber);
MyCommand.Parameters.AddWithValue("#_OrderDateTime", OrderDateTime);
MyCommand.ExecuteNonQuery();
}
}
I used AddWithValue in my example but you don't use this method. Use Add method overload as you did with proper MySqlDbType, not SqlDbType.

Should I use datatable to store one column of select query in asp.net

My sql select query will return one column of company names (many rows of names). Now I want to store it. I used:
try
{
connection.Open();
sqlCmd = new SqlCommand(sqlCmd.CommandText, connection);
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Clear();
sqlReader.Read();
dt.Load(sqlReader);
Then I tried to access the name by
dt.Rows[0][0].ToString()
dt.Rows[1][0].ToString()
dt.Rows[2][0].ToString()
etc.
But I recognize that the value in dt.Rows[0][0].ToString() is different from time to time, event if I use the same query, and it looks like that the old values still stored in the datatable event if I use new query value.
How is the right way to store and retrieve values here?
You can use,
string compnay_name = dt.Rows[0]["column_name"].ToString();
Try using your compnay name column in double quote.
You can use it in a for or foreach loop.
as,
for(int i=0;i<count;i++)
{
string compnay_name = dt.Rows[i]["column_name"].ToString();
}
Hope it helps...
Aki

Using Retrieved Data from a Parameterized SQL Query

If I'm using a parameterized query (ASP.NET with C#) in SQL, such as
var db = Database.Open("Database1");
SqlCommand cmd = new SqlCommand("SELECT * FROM pageinfo WHERE pageID = #pageID");
cmd.Parameters.AddWithValue("#pageID", 1);
And later on in the page, I want to do a foreach loop of whatever data was retrieved:
foreach(var row in ???)
What would I use (in place of the ???) to access the data I just retrieved?
Thanks.
It depends on how you execute a query.
Usually it's done by SqlCommand.ExecuteReader
For example, in your case, you can:
....
SqlDataReader reader = cmd .ExecuteReader();
while (reader.Read())
{
...
}
But there are also other ways to rertieve the data, for example using DataSet
For a complete example on how to do that can have a look on:
Using ADO.NET for beginners
You can use while iteration statement with SqlCommand.ExecuteReader instead of foreach. Take a look this;
var db = Database.Open("Database1");
SqlCommand cmd = new SqlCommand("SELECT * FROM pageinfo WHERE pageID = #pageID");
cmd.Parameters.AddWithValue("#pageID", 1);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0]);
}
reader[0] returns first row of first column and reader[1] returns first row of second column if your data has of course.

C# List<int> populated from SQL Stored Procedure results

I'm using C# in VS 2005 (.NET 2.0) and SQL Studio 2005 on an older CMS made in the mid-'00s. I'm tasked with creating a new permission gate that allows only certain users to see certain parts of the site.
I need help populating a List list based on feedback I got when I posted this question: Populate ArrayList from Stored Procedure result set
So, now, how do get get the values from the stored procedure into a List? I realize this is a novice question but I'm a novice...
Any help is greatly appreciated.
Assuming you are getting your results from a DataReader, all you have to do is read each row to add the value to a list.
List<int> ReadList(IDataReader reader)
{
List<int> list = new List<int>();
int column = reader.GetOrdinal("MyColumn");
while (reader.Read())
{
list.Add(reader.GetInt32(column));
}
return list;
}
Remember to dispose of the DataReader when you are done with it.
You can try using the model located on this MSDN page under Using Parameters with a SqlCommand and a Stored Procedure. The example is shown here:
static void GetSalesByCategory(string connectionString, string categoryName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create the command and set its properties.
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "SalesByCategory"; //Stored Procedure Name
command.CommandType = CommandType.StoredProcedure;
// Add the input parameter and set its properties.
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#CategoryName";
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = categoryName;
// Add the parameter to the Parameters collection.
command.Parameters.Add(parameter);
// Open the connection and execute the reader.
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
//Instead of displaying to console this is where you would add
// the current item to your list
Console.WriteLine("{0}: {1:C}", reader[0], reader[1]);
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
}
it depends on how you have retreived the results
reader?
dataset?
something else?
walk through the results using
foreach (int item in object...) {
List.Add(item);
}
or possibly (I dont remember the exact DataRow syntax off the top of my head...)
foreach (datarow row in object.table[0].rows) {
List.Add(row[0]);
}
IList<int> myInts = new List<int>();
using (IDbConnection connection = new SqlConnection("yourConnectionStringGoesHere"))
{
using (IDbCommand command = new SqlCommand("spName", connection))
{
command.CommandType = CommandType.StoredProcedure;
//command.Parameters.Add(...) if you need to add any parameters to the SP.
connection.Open();
using (IDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
myInts.Add(Int32.Parse(reader["someIntField"].ToString()));
}
}
}
Since you already have the table the idea would be to iterate over that table while adding the IDs of the vendor into a list.
List<VendorID_Data_Type> myList = new List<VendorID_Data_Type>();
foreach(DataRow r in GetAllVendors().Rows)
{
myList.Add(r["VendorID"]);
}
What I ended up doing is using a DataTable as an intermediary data type, which is populated by the stored procedure. Then, refactoring the DataTable as the data-source in a foreach loop, I populated the List. I needed to open a second question to get to this conclusion: 2-Column DataTable to List<int> .NET 2.0

Categories

Resources