0

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

4
  • 2
    you forget to call dataGrid.DataBind() method Nov 13, 2012 at 6:33
  • Ah Ok Mohsen but ds is already blank, wat about that ?
    – Luckyy
    Nov 13, 2012 at 6:39
  • what is the value of numRows, is it 0 or not ? Nov 13, 2012 at 6:57
  • 1
    ExecuteScalar() does not return a count like you seem to be expecting. It returns the first column of the first row...all other columns/rows are ignored.
    – ethorn10
    Nov 13, 2012 at 7:03

3 Answers 3

1

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

1
  • I sent my comment as answer with more details . Nov 13, 2012 at 16:58
0

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.....

0

There were two problems in your code:

  1. 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]";
    
  2. 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.