I want to show the Database Values in a table in asp.net.
The below code is a simple query:
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = new SqlConnection("");
cmd.CommandText = "SELECT * FROM Customers ORDER BY CustomerID";
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
How can the table demonstrate DB Values? (Code needed)
You have several missing pieces in your code such as missing connection string, not relating the command to the connection and using ExecuteNonquery.
This is a good example of what you want to do: MSDN-DataGridView DataSource. While the example is not for Windows Forms, the same code for data access in the method GetData still applies.
in your application you could use the filled table (from the example) as in:
MyDataGrid.DataSource = GetData("Select * from Customer")
MyDataGrid.DataBind();
Alternatively, You can also use Visual Studio environment to connect your data grid view to the DataSource without writing code.
The above is just a simple example there are different better ways to do the same thing. However, this is a start.
As others have mentioned in the comments, you need a DataList, Gridview or Repeater on your page to bind to this data. Without it you're connecting but not displaying what you get.
The easiest thing to do would be drop a Gridview on the page and set its datasource to your command object. You need to define a CommandType on the command, too, or you'll probably throw an error.
GridView1.DataSource = cmd;
GridView1.DataBind();
You're also missing a Try...Catch...Finally with the Close() call in the Finally block. If you don't do that you could wind up with zombie connections that'll trash performance in your database.
Related
I ask the above question because I am seeing something property HasRows in the QuickWatch window..
I am modifying someone else's code, and need to follow the patterns established. I have to query a SQL Server table to retrieve a row from a configuration table, and decided to first code it in a test console app. I also decided to use the SQLClient types, and made use of property HasRows:
....
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
....
When I went to move the code to the other project, I noticed that IDataReader was used, and Intellisense said that the HasRows property wasn't available, so I used a while loop, even though I only have one row returning:
....
using (IDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
....
However when I performed a quick watch on the IDataReader rdr, I saw the HasRows property!
So can I easily get to the HasRows property for the IDataReader? If it really exists?
No you can't. HasRows is an abstract method of DbDataReader and IDataReader don't have it.
Even so DbDataReader implements IDataReader it is implemented inside DbDataReader and not in interface itself.
Use DbDataReader in your code instead of interface.
Like the title suggest, I would like to ask, is there any other way to store data from database, other than using dataset or datatable in ASP.NET?
I'm currently using something like this:
Public Function openDataTable(ByVal query As String) As DataTable
Try
If con.State <> ConnectionState.Closed Then con.Close()
con.Open()
dt = New DataTable
adap = New SqlDataAdapter(query, con)
adap.Fill(dt)
con.Close()
Catch ex As Exception
MsgBox.Message)
End Try
Return dt
End Function
dt = conn.openDataTable("Select * From Employee")
It worked fine for me, but I would like to know, is there any other way to do it?
And if there is another way, would someone be so kind as to give me an example? Thanks.
In .net framework 3.5 and above you can use linq with entity framework.
Start here:
Getting Started with LINQ in C#
Entity Framework
A very good Entity framework Tutorial: http://www.codeproject.com/Articles/363040/An-Introduction-to-Entity-Framework-for-Absolute-B
Introduction to LINQ: http://msdn.microsoft.com/en-us/library/bb397897.aspx
Getting Started with LINQ in Visual Basic
Yes. You could:
Run SQL Statements directly
Use Linq to SQL
Use Entity Framework
Good morning,
I have an ASPX page with an UpdatePanel containing a Gridview and SqlDataSource control. In the SqlDataSource control I specify an InsertCommand. I would like to be able to read the InsertCommand that my page will send to the SQL database. Reading the following
mySqlDataSource.InsertCommand
in code-behind gives me the InsertCommand with #parameters rather than the actual value for each parameter that will be sent to SQL.
Is there a way to read the final InsertCommand that will actually be sent to the database for execution?
EDIT: Please note, my question could apply to Select, Update, Insert or any command that is sent from my ASPX page to SQL. The command must be converted to a language that SQL can interpret and execute and that is the very version of the command that I am trying to read.
Thank you.
I guess you should subscribe to the Inserting event of your DataSource.
Then, in your Inserting_Handler, you may browse the your DataSource.InsertParameters Collection
private void On_Inserting(Object sender, SqlDataSourceCommandEventArgs e)
{
var txt = e.Command.CommandText;
//the parameters names and values are in e.Command.Parameters
}
Hope this will help
I am using ASP.NET. I have a ReportPage1 and ReportOutputPage1. These are different aspx files and has different MasterPages. However, I need the same SqlDataSource object to use on both pages. On ReportPage I need SqlDataSource to call StoredProcedure and import data to CSV file, but on ReportOutputPage I need to use SqlDataSource to call the same StoredProcedure and populate GridView.
ReportPage1 is "main" page - a button click from this page opens ReportOutputPage1 and displays it in new window. ReportPage is PreviousPage for ReportOutputPage1.
Above is example for Report1. The same idea is for Report2 (with SqlDataSource2) and for Report3 (SqlDataSource3) etc. - 10 different reports.
How to reuse SqlDataSource for every two pages (ReportPage & ReportOutputPage)?
First suggestion I found in web - using masterpage for both ReportPage and ReportOutputPage. This doesn't work, as I have already have different masterpages for ReportPage and ReportOutputPage, as well as then I need to create 10 different MasterPages for each Report.
Second suggestion was to define SqlDataSource on ReportPage and then reuse it using PrevousePage on ReportOutputPage, but this doesn't work for my special case (I am using Ajax staff and Partial page postbacks and I am loosing PreviousPage, also SqlDataSource could not be serialized to save it in ViewState or similar).
Create UserControl. Probably this could work, but it is time consuming to create UserControl every time for new Report (10 reports - 10 usercontrols?).
Simply Copy & Paste SqlDataSource (I did it for one Report) could work, but I would like something more like code reuse. Someone could simply forget to modify SqlDataSource in two different places if necessary.
Can you, please, give me some suggestions how to reuse code (particularly, SqlDataSource) for Report & ReportOutput pages?
Could you define the need for using the same SqlDataSource? If they are two different pages and it sounds like two different uses why not use two different SqlDataSource? The pages are separate anyhow, your not going to be able to share an object on one with the other.
I would suggest you look at adding a data layer to your application for database interaction and binding your data to the datagrid at request time. That way you build your database interaction once and reuse that over different pages.
The other option is you simply use two SqlDataSources and copy/paste them to both the pages. If your trying to make a selection or some sort of criteria apply to your second page then consider using query strings and QueryStringParameters in your SqlDataSource.
Hope this helps.
Edit: Pop this in App_Code somewhere, pass in your specific usage requirements.
Public Shared Function GetData(connString As String, command As String, Optional params As SqlParameter() = Nothing) As DataTable
Dim conn As New SqlConnection(connString)
Dim da As New SqlDataAdapter(command, conn)
Dim dt As New DataTable
da.SelectCommand.CommandType = CommandType.StoredProcedure
da.SelectCommand.CommandTimeout = 6000 '6 seconds.
If Not IsNothing(params) Then
For Each p As SqlParameter In params
da.SelectCommand.Parameters.Add(p)
Next
End If
Try
conn.Open()
da.Fill(dt)
Return dt
Catch ex As Exception
Throw ex
Finally
conn.Close()
End Try
End Function
Then bind the datatable to your gridview, not sure how your outputing to file.
Private Sub BindData(gridview As GridView, data As DataTable)
gridview.DataSource = data
End Sub
You can now re-use the database interaction from the code behind:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
BindData(MyGridView,GetData(ConnectionStrings(connName).ConnectionString, _
"dbo.SomeSprocOrOther", _
New SqlParameter(){New SqlParameter("paramName","paramValue")})
End Sub
I wrote this type of command for my application.BUT my lecturer told me those things are Old fashion,USE new things like DATASET.. I wanted to know you guys is that correct ? Those kind of thigs are outdated ? Date Set is new way to do this ?
protected void btn_edit_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(CONN_STR))
{
con.Open();
using(SqlCommand cmd = new SqlCommand("UPDATE tbl_BinCardManager SET ItemName = #ItemName WHERE ItemNo = #ItemNo"), con)
{
// TODO: fill in param values with real values
cmd.Parameters.AddWithValue("#ItemName", "my item name");
cmd.Parameters.AddWithValue("#ItemNo", 1);
cmd.ExecuteNonQuery();
}
}
}
The classes you are using are the nuts and bolts of pretty much all data access technologies in .NET. There are abstractions around it such as DataSets, LINQ to SQL, Entity Framework, etc. But in the end they all use SqlConnection and friends.
In fact, of the 3 technologies I mentioned, DataSets are the ones that have been largely discarded and have little or no support outside of the .NET 2.0-era tooling.
DataSet used DataReader internally to populate date. Also dataset works in disconnected mode, but your code is not outdated by any means.
Your teacher is may be talking about using ORM.
NO, your code is not at all Old fashioned..its perfectly simple for your requirement.
use DATASET when its really needed.. like, when you want to take some data offline, and modify it and again reflect back the changes to database..
In fact SqlCommand command is not an alternative for DATASET..
DATASET is something which can hold tables retrieved from database or locally created..
SqlCommand is something which helps you get/insert/update data from/to database table
even if you are using DATASET you still need SqlCommand.. then there is no question of Sqlcommand being oldfashioned and Dataset being the new one