Select SQL Server table data using ASP.NET - asp.net

I want to select/retrieve all data from SQL Server using ASP.NET.
I've tried this code...
SqlCommand cmdd = new SqlCommand("select * from comment where ID='" + st + "'", con);
SqlDataReader drr;
drr = cmdd.ExecuteReader();
while(drr.Read())
{
user_name.Text = drr["Username"].ToString();
date.Text = drr["Date_Created"].ToString();
userrcomment.Text = drr["Comment"].ToString();
}
The code works fine but it can select only one record from database but I want to select all the records...
Also can any one tell me that how to use two/multiple queries using only one data reader....
Any help will be appreciated...
Update: problem is when the query run then only the last record will show, but I want that all the record will show against the mentioned id...
Update 2 this is my page code, as I am new in asp.net, so how can I get the username and other data in span or p tag...
<asp:Panel ID="Panel1" runat="server" Height="140px" Width="378px">
<p>
<asp:Label ID="user_name" runat="server"></asp:Label> Commented on <asp:Label ID="date" runat="server"></asp:Label></p>
<asp:Label ID="userrcomment" runat="server" Height="31px" Width="378px"></asp:Label>
</asp:Panel>

If you are getting only one records then there are two possibilities.
"select * from comment where ID='" + st + "'" In your where condition satisfy for only one record.
You are using SqlDataReader in while loop if there are many records you got but you can only see last record bcoz it will be overwrite last record in every loop.
while(drr.Read())
{
user_name.Text = drr["Username"].ToString();
date.Text = drr["Date_Created"].ToString();
userrcomment.Text = drr["Comment"].ToString();
}
the user_name.Text will replaced with last record.

Assuming your code is otherwise working, and you want to see all the data in just the three text boxes instead of some more tabular format.
SqlCommand cmdd = new SqlCommand("select * from comment where ID='" + st + "'", con);
SqlDataReader drr;
drr = cmdd.ExecuteReader();
while(drr.Read())
{
user_name.Text += drr["Username"].ToString();
date.Text += drr["Date_Created"].ToString();
userrcomment.Text += drr["Comment"].ToString();
}
Notice instead of overwriting the value of the textbox, I'm appending strings to it because I used +=. You might want to concatenate a , to it also.
More likely with multiple records though, you want to have them get in a table. The easiest and most straightforward way to do this is:
Code Behind
var cmd = new SqlCommand("select * from comment where ID=#id");
cmd.Parameters.AddWithValue("id", st);
var dt = new DataTable();
using(var con = new SqlConnection(connectionString))
{
con.Open();
dt.Load(cmd.ExecuteReader());
}
GridView1.DataSource = dt;
GridView1.DataBind();
Markup
<asp:GridView runat="server" id="GridView1" AutoGenerateColumns="true" />

You can execute multiple select queries using a single DataReader. There is an article namely,"Executing multiple SQL statements as one against SQL Server" in CodeProject. Please read it, you will get solution for sure.
using(SqlConnection conn=new SqlConnetion(ConnectionString))
{
using(SqlCommand cmdd = new SqlCommand("select * from comment where ID='" + st + "'", con))
{
using(SqlDataAdapter adapter=new SqlDataAdapter(cmdd))
{
DataTable dt=new DataTable();
adapter.Fill(dt);
//Bind the datasource with a repeater control in which you can place textbox control. It will repeat for every data rows.
}
}
}

You need to place the record into a dataset for you to get all the data you're trying to Retrieve
SqlCommand cmdd = new SqlCommand("select * from comment where ID='" + st + "'", con);
SqlDataReader drr = new SqlDataReader(cmdd);
DataSet ds = new DataSet();
da.Fill(ds);
foreach(DataRow dr in ds.Tables[0].Rows)
{
user_name.Text = dr["Username"].ToString();
date.Text = dr["Date_Created"].ToString();
userrcomment.Text = dr["Comment"].ToString();
}

select/retrieve all data from SQL-Server using ASP.NET
using this SqlDataReader (sqldr) GetValue for all the records
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringsName"].ConnectionString);
string sql = "select * from comment where ID='" + st + "'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader sqldr = cmd.ExecuteReader();
if (sqldr.Read() == true)
{
user_name.Text = sqldr.GetValue(2).ToString();
date.Text = sqldr.GetValue(3).ToString();
userrcomment.Text = sqldr.GetValue(4).ToString();
}
sqldr.Close();
con.Close();

Related

Adding '% into SQL Command

I have an SQL Query that i want to run throw my asp.net (WebForms) Project
The Query is:
SELECT COUNT([order]) FROM menu_orders_Finished
WHERE [order] LIKE '%EXAMPLE%'
What i'm trying to do is
con.Close();
con.Open();
cmd = new SqlCommand("select * from menu",con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
Series series = Chart2.Series["Series2"];
while (dr.Read())
{
search = new SqlCommand("SELECT COUNT([order]) FROM menu_orders_Finished WHERE [order] LIKE '%#order#%'", con);
search.Parameters.AddWithValue("#order", dr["name"].ToString());
int count = Convert.ToInt32(search.ExecuteScalar());
Label3.Visible = true;
Label3.Text += count.ToString() + "+";
}
con.Close();
Which is Basically Counting how many times i'm having an order with one my menu items in the order (I want to make a chart of the best selling meal)
And then adding it in the chart (But i toke it off just to see what i get first)
I think you want string concatenation:
search = new SqlCommand("SELECT COUNT([order]) FROM menu_orders_Finished WHERE [order] LIKE CONCAT('%', #order, '%')", con);

Run sp_msforeachdb to select dbsize used in c#

I have a query as such:
EXEC sp_msforeachdb
'USE [?];
SELECT DB_NAME() AS [Database Name],
CAST(SUM(FILEPROPERTY(name, ''SpaceUsed''))/128.0 AS decimal(18,2)) AS [Used space(MB)]
FROM sys.database_files
Where type_desc = ''ROWS'' and
GROUP BY type_desc'
and executing this in MSSM is alright.
My problem is that I need to execute this in my application using c# and stored in a Datatable. Any idea how to do this?
Tried looking for at CommandType.StoredProcedure and CommandType.Textbut still can't figure it out.
FYI, I'm not allowed to create a new stored procedure for this.
EDIT (SAMPLE CODE)
using (SqlConnection sqlConnection = new SqlConnection(HoustonSqlCon))
{
const string query = "EXEC sp_msforeachdb 'USE [?]; SELECT DB_NAME() AS[Database Name]," +
"CAST(SUM(FILEPROPERTY(name, ''SpaceUsed'')) / 128.0 AS decimal(18, 2)) AS[Used space(MB)]" +
"FROM sys.database_files" +
"Where type_desc = ''ROWS''" +
"GROUP BY type_desc'";
using (SqlCommand comm = new SqlCommand(query, sqlConnection))
{
sqlConnection.Open();
comm.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.Fill(totalSchemas);
}
}

Response.write only shows the first record from the database (this.session.sessionid)

I've got a problem for the past few days. I will explain short what i've did.
I have a table created in the database called 'Cart'. This Cart cointains: ClientID, Artical number, and quantity. In the ClientID, a session.sessionID stored. In the Artical just a number like 1012. And in quantity a number like 1 or 3.
What I would like to, is retrieve all the records, with the session.session id of the user.
It does work in the page, but only the first record of the like 4-5 records that are in the cart table is shown. I think i comes due the problem that it looks for this.session.sessionidand when it found one, it doesn't look any further then that.
I've tried to loop through the query where sessions is. But it won't let me loop because it doesn't know for? Even if I loop the whole query outside of it like this:for (int i = 0; i < sessies.Length; i++) It will show more records.. but they are all the first records.. I know that was a stupid try but I can always try..
Looked for all over the internet but couldn't find the solution to this.
Hope to get a response soon from somebody. It would be gratefull.
Used the following code:
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["GarageConnectionString"].ToString()))
{
string sessions = this.Session.SessionID;
SqlCommand cmd = new SqlCommand("SELECT * FROM cart where ClientID='" + sessions + "'", cn);
cn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
rdr.Read();
TextBox1.Text = rdr[2].ToString();
Response.Write("<br>" + ("Sessie id "+rdr[1].ToString()));
Response.Write("<br>" + ("Artikel nummer "+rdr[2].ToString()));
Response.Write("<br>" + ("Aantal "+rdr[3].ToString()));
cn.Close();
}
SqlDataReader advances to the next record in the set: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.read%28v=vs.110%29.aspx
Call Read() in a loop, like so:
using (SqlConnection cn = newSqlConnection(ConfigurationManager.ConnectionStrings["GarageConnectionString"].ToString()))
{
string sessions = this.Session.SessionID;
SqlCommand cmd = new SqlCommand("SELECT * FROM cart where ClientID='" + sessions + "'", cn);
cn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (rdr.Read())
{
TextBox1.Text = rdr[2].ToString();
Response.Write("<br>" + ("Sessie id "+rdr[1].ToString()));
Response.Write("<br>" + ("Artikel nummer "+rdr[2].ToString()));
Response.Write("<br>" + ("Aantal "+rdr[3].ToString()));
}
cn.Close();
}
You should loop through the datareader: ie:
while (rdr .Read())
{
Console.WriteLine("{0}\t{1}", rdr .GetInt32(0),
rdr .GetString(1));
}
Each call to SqlDataReader.Read() gets a single row, unless there are no more rows when it returns false.
So you need to loop to get all rows:
while (rdr.Read()) {
// Use rdr methods to access the values from the current row.
}
Use While Loop- Example
if (rdr .HasRows)
{
while (rdr .Read())
{
Console.WriteLine("{0}\t{1}", rdr .GetInt32(0),
rdr .GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
rdr .Close();

Comparing cyrillic data from SQL Server table and Excel file with ASP.NET

Using ASP.NET I need to compare data loaded from Excel file with data in SQL Server table. It's data written in cyrillic.
Basically, after script creates an array list filled with data from database table, it opens Excel file, and list data from one of the column. For every data stored in Excel cell, I have to find position in mentioned array list.
I have same data in both sources, but script returns that there are no same data at all. I guess that is something related with cyrillic letters.
Part of the code used for reading Excel cells and comparing with array list looks like this:
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
Page.Trace.Write(getExcelSheetName);
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dtExcelRecords);
con.Close();
foreach (DataRow row in dtExcelRecords.Rows)
{
Response.Write(row[0]);
Response.Write(" ");
Response.Write(MyClass.areasList.IndexOf(row[0])); // always returns -1
Response.Write(Environment.NewLine);
Response.Write("<br />");
}
Can you help me solving this please? Thank you in advance!

asp.net how to decrypt each label value in a gridview

i have an gridview that retrieves the data via a datatable like this:
protected DataTable allClients()
{
string conn, comm, tSub, tMain;
tSub = "client_sub";
tMain = "client_main";
conn = ConfigurationManager.ConnectionStrings["localsqlserver"].ConnectionString;
comm = "SELECT * FROM [" + tSub + "] t1 LEFT JOIN [" + tMain + "] t2 ON " +
"t1.customer_ID = t2.customer_ID";
SqlConnection connection = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand(comm, connection);
connection.Open();
DataTable allTable = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(allTable);
connection.Close();
return allTable;
}
clientGrid.DataSource = allClients();
clientGrid.DataBind();
and its working fine on retrieving the data but the problem is i am trying to decrypt the value on retrieving it.
i used this encryptor class
so how can decrypt the value of each row in the gridview.
using asp.net 4.0, thanks
Two options - you can loop around the data table in your allClients() method before returning it, or you can look into handling the row bound events when you do the data bind on the grid view - this would allow you to access each row as its created in the grid view and manipulate the data displayed.

Resources