Unable to retrieve values from database in asp.net - asp.net

I am doing first asp.net app, now need to connect it to SQL (Using MS SQL 2008), but I am unable to get any value from the tables.
My web.config is:
<add name="MainConnectString" connectionString="Data Source=LUCKYY-PC;initial catalog=testDbName;uid=sa;Password=123456;Integrated Security=True" providerName="System.Data.SqlClient" />
In backend Code:
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MainConnectString"].ConnectionString))
{
string query = "select * from [testTableName]";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
string numRows = cmd.ExecuteScalar().ToString();
SqlDataAdapter da = new SqlDataAdapter(query, conn);
DataSet ds = new DataSet();
da.Fill(ds);
dataGrid.DataSource = ds;
conn.Close();
}
dataGrid is the datagrid name i have defined on ascx page of this code.
but 'ds' appears with 0 count, and so the datagrid is blank, I don't know if I am missing anything on code or in web.config ...any help will be appreciated

dataGrid.DataBind() - filled the datagrid, thanks Mohsen

Check your connection string. I think you had make mistake in writing data source, I think you are using SQL server 2005/2008/2008 R2, and so data source must be to set as .(DOT) or localhost. Try this one may be it can help you.....

There were two problems in your code:
As #ethorn10 commented, ExecuteScalar() as you are using it won't give you what you expecting. Change your query to:
string query = "select count(*) from [testTableName]";
You have forgotten to call the datagrid DataBind() method to show the records selected from datasource.
dataGrid.DataSource = ds;
dataGrid.DataBind();
If you are new to asp.net, I strongly recommend you to learn and use Entity framework instead of using the old ADO.net code like yours.

Related

ASP.NET Pros and Cons of two different ways of displaying data on website

I know of two ways to display data on a website.
The first is by using adding a DB connection to the Server Explorer and then dragging the table you want to display on the webpage. Visual Studio does all the backend stuff for you.
The second is where you just choose the control you want to use and you hook it up manually through code for it to display the data you want. You do not have to connect to the DB in server explorer. Something like this in code behind:
SqlConnection sqlConnection = new SqlConnection(connString);
SqlCommand command = new SqlCommand("RawToSummary", sqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#SDate", SqlDbType.Date).Value = MySDate;
command.Parameters.Add("#EDate", SqlDbType.Date).Value = MyEDate;
sqlConnection.Open();
command.ExecuteNonQuery();
sqlConnection.Close();
private DataTable FillData(string connString, SqlCommand cmd)
{
SqlConnection conn = new SqlConnection(connString);
DataTable dt = null;
try
{
cmd.Connection = conn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds, "tableName");
dt = ds.Tables["tableName"];
}
catch (Exception e)
{
WriteLog("Error: " + e);
}
finally
{
conn.Close();
}
return dt;
}
I have 2 questions:
1) What is the second method called? I am trying to learn more about it but need a Google search term for it.
2) What are the pros and cons of each method?
I am using the following: Visual Studio 2010, SQL Server Management Studio 2008
Server Explorer/Database Explorer is the server management console for Visual Studio. Use this window to open data connections and to log on to servers and explore their system services.
With Server Explorer/Database Explorer we can view and retrieve information from all of the databases connected to. like:
List database tables, views, stored procedures, and functions
Expand individual tables to list their columns and triggers
Right-click a table to perform actions, such as showing the table's
data or viewing the table's definition, from its shortcut menu.
Programmatic approach
Second approach is the programmatic approach to perform the DM (data manipulation) and DD (data definition) functions.
Server Explorer/Database Explorer goes through the same course (connecting with database, query tables etc.) but in the background while in programmatic approach we write commands (queries/stored procedures) for the same.
I hope this gives an idea.

Getting an empty DataSet table from Oracle Client in .NET

Hi have this simple ASPX site setup. In the code behind, I'm connecting to an Oracle database, throwing a SELECT query and putting the result to a DataSet that I can then use/display on the website.
The problem: The query should give me result (works fine inside SQLDeveloper), but when I'm filling the DataSet, it gives me 0 rows every time. No Oracle errors show up, connection to the database opens up fine and the query looks correct.
I would have liked to get some kind of an Oracle error, that would have been easier to troubleshoot. I have tried to find a solution online, but haven't found anything that has helped with my problem.
Here is the relevant code I'm using:
using System.Data.OracleClient;
private OracleConnection conn = new OracleConnection();
-- // Below everyting is in the same method
var ds = new DataSet();
-- // conn.ConnectionString is corretly set
conn.Open(); // connection to database is opened
OracleCommand command = conn.CreateCommand();
var sql = "SELECT * FROM someTable"; -- // the SQL query
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
OracleDataAdapter adapter = new OracleDataAdapter(command);
ds.Tables.Clear();
adapter.Fill(ds);
Here the DataSet (ds) should be full, but it's always empty. Any pointers would be most welcome. Please let me know if I'm missing some information.

Crystal Reports and strongly typed datasets yields empty report

I am converting an ASP.Net app from VS 2003 to VS 2005 as a starting point. The app uses Crystal Reports and binds using ADO.Net to a strongly typed dataset (XSD). I had to change some of Crystal Code to work with the newer version of Crystal. Now, when I run the page, the report generates, but none of the fields fill in. I have seen lots of people having the same problem with no real solutions out there. I decided to create a fresh project that does the same thing to remove the conversation from VS 2003 to 2005 as a possible cause of the problem. So my sample program has a button that runs a query, fills the dataset and assigns it to the report. The report displays the headers only. The code is below. I have no idea what to try next.
DataSet1 ds = new DataSet1();
SqlConnection conn =
new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("select * from mytable", conn);
da.Fill(ds);
ReportDocument rep = new ReportDocument();
rep.Load(Server.MapPath("crystalreport.rpt"));
rep.SetDataSource(ds);
CrystalReportViewer1.ReportSource = rep;
CrystalReportViewer1.RefreshReport();
I also created the DataSet1.XSD based on the same MYTABLE table. I get no errors or any indication anything is wrong except that the fields in the report don't populate.
It would take some debugging to know for sure why it's not working for you. Have you looked at the resulting dataset in a debugging session, and seen if it fills correctly?
Here's a good example of a method to work from.
SqlConnection cnn;
string connectionString = null;
string sql = null;
connectionString = "data source=SERVERNAME;initial catalog=DATABASENAME;user id=USERNAME;password=PASSWORD;";
cnn = new SqlConnection(connectionString);
cnn.Open();
sql = "select * from mytable";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet1 ds = new DataSet1();
dscmd.Fill(ds, "mytable");
cnn.Close();
CrystalReport1 objRpt = new CrystalReport1();
objRpt.SetDataSource(ds.Tables[1]);
crystalReportViewer1.ReportSource = objRpt;
crystalReportViewer1.Refresh();

SQL Server 2005

i created one ASP.Net project using SQL Server 2005 .I successfully inserted .But i dont know to view the table.Please tell me
A beginner instrudciton into SQL server seems in order - you seem to stumble around not knowing anything about hwat you really deal with.
I suggest heading over to ASP.NET (http://www.asp.net/) and read the indroduction documentation, as well as have some look at the sample code and the beginner forum.
Well this is a pretty broad question, but to get data into a datatable you could do something like:
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand("Retrieve", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = ID;
SqlDataAdapter sqldata = new SqlDataAdapter(cmd);
con.Open();
sqldata.Fill(dt);
con.Close();

error in mysql connection "The given key was not present in the dictionary"

I have problem while connecting to mysql database using "ADO.NET Driver for MySQL (Connector/NET)"
I got this exception The given key was not present in the dictionary.
Edit:
MySqlConnection con = new MySqlConnection("Server=localhost;Database=pgs_db;Uid=root;Pwd=;");
MySqlCommand com = new MySqlCommand();
com.CommandType = CommandType.StoredProcedure;
com.Connection = con;
com.CommandText = "getStudent";
con.Open();
MySqlDataReader dr =com.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
con.Close();
sorry i was using a worng connectionstring
this is a right one :
"server=localhost; user id=user; password=password; database=mydatabase; pooling=false;"
thnx Oded
Without seeing the code, I am guessing you are trying to access a configuration key that does not exist in your application config file.
Edit:
After seeing the code sample, the problem is probably not with connecting to the DB.
I would say that in your GridView, you are binding to a field that is not returned by the DB query.

Resources