I have to display bar chart using ajax extender tool. I have to display information on chart when I am selecting one value from drop down list. But it shows "Must declare a scalar variable" error. Please help me.
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select Name from aTable";
DataTable dt = GetData(query);
ddlCountries.DataSource = dt;
ddlCountries.DataTextField = "Name";
ddlCountries.DataValueField = "Name";
ddlCountries.DataBind();
ddlCountries.Items.Insert(0, new ListItem("Select", ""));
}
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["demoConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
{
string query = string.Format("select Debit, Credit, Year From aTable where Name=#Name", ddlCountries.SelectedItem.Value);
DataTable dt = GetData(query);
string[] x = new string[dt.Rows.Count];
decimal[] y = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
BarChart1.Series.Add(new AjaxControlToolkit.BarChartSeries { Data = y });
BarChart1.CategoriesAxis = string.Join(",", x);
BarChart1.ChartTitle = string.Format("{0} Order Distribution", ddlCountries.SelectedItem.Value);
if (x.Length > 3)
{
BarChart1.ChartWidth = (x.Length * 100).ToString();
}
BarChart1.Visible = ddlCountries.SelectedItem.Value != "";
}
In this line
string query = string.Format(#"select Debit, Credit, Year
From aTable where Name=#Name",
ddlCountries.SelectedItem.Value);
you have a parameter placeholder #Name but you don't add the required parameter to the SqlCommand that executes the sql. This produces the error that you see.
(By The way, string.Format requires the placeholder in the form {0}, but also if you fix that problem it is still wrong because you leave open the door to Sql Injection)
Fixing it requires a change in your GetData function.
You need to add an (optional) parameter array as another argument
private DataTable GetData(string query, SqlParameter[] prms = null)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["demoConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
if(prms != null)
cmd.Parameters.AddRange(prms);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
And now, when you call that method, you could write
string query = "select Debit, Credit, [Year] From aTable where Name=#Name";
SqlParameter[] prms = new SqlParameter[1];
prms[0] = new SqlParameter("#Name", SqlDbType.NVarChar).Value =
ddlCountries.SelectedItem.Value.ToString());
DataTable dt = GetData(query, prms);
Notice also that I have put the field Year between square brackets. Year is the name of a T-SQL Function and you should use this trick to avoid to confuse the SQL Parser
Related
I am trying to store sql data that I have for a voucher id and voucher amount into a variable and display it into a label on a click of a button.
protected void Button1_Click(object sender, EventArgs e)
{
string voucherId = String.Empty;
string voucherAmount = String.Empty;
string queryVoucherId = "select voucherid from ReturnForm where email = '" + Session["username"] + "';";
string queryVoucherAmount = "select voucheramount from ReturnForm where email = '" + Session["username"] + "';";
int index = 0;
using (SqlConnection con = new SqlConnection(str))
{
SqlCommand cmd = new SqlCommand(queryVoucherId, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
voucherId = reader[index].ToString();
index++;
}
}
using (SqlConnection con = new SqlConnection(str))
{
SqlCommand cmd = new SqlCommand(queryVoucherAmount, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
voucherAmount = reader[index].ToString();
index++;
}
}
if (txtVoucher.Text == voucherId)
{
Label3.Visible = true;
Label3.Text = voucherAmount;
}
}
When I click the button its giving me an error saying that the index is out of bounds.
Building on #JSGarcia's answer - but using parameters as one ALWAYS should - you'd get this code:
string email = Session['username'];
string query = $"SELECT voucherid, voucheramount FROM ReturnFrom WHERE Email = #email";
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
// set the parameter before opening connection
// this also defines the type and length of parameter - just a guess here, might need to change this
cmd.Parameters.Add("#email", SqlDbType.VarChar, 100).Value = email;
conn.Open();
sda.Fill(dt);
conn.Close();
}
Personally, I'd rather use a data class like
public class VoucherData
{
public int Id { get; set; }
public Decimal Amount { get; set; }
}
and then get back a List<VoucherData> from your SQL query (using e.g. Dapper):
string query = $"SELECT Id, Amount FROM ReturnFrom WHERE Email = #email";
List<VoucherData> vouchers = conn.Query<VoucherData>(query).ToList();
I'd try to avoid the rather clunky and not very easy to use DataTable construct...
I strongly recommend combining your sql queries into a single one, write it into a datatable and continue your logic from there. IMHO it is much cleaner code:
string email = Session['username'];
string query = $"SELECT voucherid, voucheramount FROM ReturnFrom where Email = '{email}'";
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = conn.CreateCommand())
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
conn.Open();
sda.Fill(dt);
conn.Close();
}
// Work with DataTable dt from here on
...
Well, one more big tip?
You ONLY as a general rule need a dataadaptor if you going to update the data table.
And you ONLY need a new connection object if you say not using the sql command object.
The sqlcommand object has:
a connection object - no need to create a separate one
a reader - no need to create a separate one.
Note how I did NOT create a seperate connection object, but used the one built into the command object.
And since the parameter is the SAME in both cases? Then why not re-use that too!!
So, we get this:
void TestFun2()
{
String str = "some conneciton???";
DataTable rstVouch = new DataTable();
using (SqlCommand cmdSQL =
new SqlCommand("select voucherid from ReturnForm where email = #email",
new SqlConnection(str)))
{
cmdSQL.Parameters.Add("#email", SqlDbType.NVarChar).Value = Session["username"];
cmdSQL.Connection.Open();
rstVouch.Load(cmdSQL.ExecuteReader());
// now get vouch amount
cmdSQL.CommandText = "select voucheramount from ReturnForm where email = #email";
DataTable rstVouchAmount = new DataTable();
rstVouchAmount.Load(cmdSQL.ExecuteReader());
if (rstVouch.Rows[0]["vourcherid"].ToString() == txtVoucher.Text)
{
Label3.Visible = true;
Label3.Text = rstVouchAmount.Rows[0]["voucheramount"].ToString();
}
}
}
I have the following method that calls a proc in my database and returns the results into a dataset. The dataset is then used to populate a table I render using MVC & cshtml.
The method is:
public DataSet CallProcToDataSet(string procName)
{
DataSet ds = new DataSet();
string constr = ConfigurationManager.ConnectionStrings["UAT"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(procName))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(ds);
}
}
}
return ds;
}
This works fine, however what I want is to have some way of paginating the results so that only 10 at a time are displayed. What is the best way for me to achieve this that doesn't involve any changes to the proc calls?
You can use this overload of the Fill method
public int Fill(int startRecord, int maxRecords, params DataTable[] dataTables);
(link: https://msdn.microsoft.com/en-us/library/0z5wy74x(v=vs.110).aspx)
This way you will only return a subset of the records without modifying your stored procedure.
Example (MSTest)
[TestMethod]
public void TestMethod1()
{
DataSet ds = new DataSet();
var procName = "sp_server_info";
string constr = ConfigurationManager.ConnectionStrings["UAT"].ConnectionString;
var tblName = "result";
var tbls = new[] { ds.Tables.Add(tblName) };
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(procName))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(0, 10, tbls);
}
}
}
Assert.AreEqual(tbls[0].Rows.Count, 10);
}
Try following :
DataSet ds = new DataSet();
DataTable dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i += 10)
{
DataTable pageTable = dt.AsEnumerable().Where((x, n) => (n >= i) && (n < i + 10)).CopyToDataTable();
}
I want to show a DataGridView with Compte Name and total sum of Recette and Depense per month and year.
I have a DateTimePicker customized with month an year.Image of the Winforms and the error
Example : if I select date = 11/2015 (November 2015), it will show like that
Compte Total
BTK 633,000
Biat 987,888
Caisse 988,875
and if I select date = 06/2016 (Jun 2016), it will show like that
Compte Total
BTK 0
Biat 653,256
Caisse 88,145
My Code :
public partial class ComptesMois : Form
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader dreader;
string connstring = "Data Source=.;Initial Catalog=Tresorerie;Integrated Security=True";
public ComptesMois()
{
InitializeComponent();
//Set Columns Count
DataGridViewCompteMois.ColumnCount = 2;
//Hide the last blank line
DataGridViewCompteMois.AllowUserToAddRows = false;
//Add Columns
DataGridViewCompteMois.Columns[0].Name = "NomCom";
DataGridViewCompteMois.Columns[0].HeaderText = "Nom de Compte";
DataGridViewCompteMois.Columns[0].DataPropertyName = "NomCom";
DataGridViewCompteMois.Columns[0].Width = 100;
//Add Columns
DataGridViewCompteMois.Columns[1].Name = "Total";
DataGridViewCompteMois.Columns[1].HeaderText = "Total";
DataGridViewCompteMois.Columns[1].DataPropertyName = "Total";
DataGridViewCompteMois.Columns[1].Width = 100;
this.BindGrid();
CompteMoisdateTimePicker.Format = DateTimePickerFormat.Custom;
CompteMoisdateTimePicker.CustomFormat = "MM yyyy";
//CompteMoisdateTimePicker.ShowUpDown = true; // to prevent the calendar from being displayed
}
private void BindGrid()
{
DataGridViewCompteMois.DataSource = null;
using (SqlConnection con = new SqlConnection(connstring))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT c.NomCom from Tresorerie t join Compte c on t.IdCom=c.IdCom", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
DataGridViewCompteMois.DataSource = dt;
}
}
}
}
}
private void DataGridViewCompteMois_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
string month = CompteMoisdateTimePicker.Value.Month.ToString();
string year = CompteMoisdateTimePicker.Value.Year.ToString();
//select * from < table > where month(searchDate) = Month_from_box and Year(searchDate) = Year_from_box
// select sum(recette + depence) from Tresorerie where
String total;
for (int i = 0; i < DataGridViewCompteMois.Rows.Count; i++)
{
conn = new SqlConnection(connstring);
conn.Open();
String NomCompteDataGrid = Convert.ToString(DataGridViewCompteMois.Rows[i].Cells[0].Value);
String IdCompteValue = "select IdCom from Compte where NomCom='" + NomCompteDataGrid + "'";
comm = new SqlCommand(IdCompteValue, conn);
int IdComValue = Convert.ToInt32(comm.ExecuteScalar());
conn.Close();
using (SqlConnection con = new SqlConnection(connstring))
{
using (SqlCommand cmd = new SqlCommand("select sum(Recette + Depense) as Total from Tresorerie where IdCom=#IdCom GROUP BY Recette,Depense", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#IdCom", IdComValue);
con.Open();
total = Convert.ToString(cmd.ExecuteNonQuery());
con.Close();
}
}
DataGridViewCompteMois.Rows[i].Cells[1].Value = total;
}
}
}
but there is an error, the result show me -1 for every Compte
Update 1: Thanks to #Soner_Gönül, I modify the query statement, and I tested it on sql and it works, but the problem when I add the result to the grid cell, it shows empty, but I try to show it with messgae box and it works, my code :
String total;
private void CompteMoisdateTimePicker_ValueChanged(object sender, EventArgs e)
{
string month = CompteMoisdateTimePicker.Value.Month.ToString();
string year = CompteMoisdateTimePicker.Value.Year.ToString();
for (int i = 0; i < DataGridViewCompteMois.Rows.Count; i++)
{
conn = new SqlConnection(connstring);
conn.Open();
String NomCompteDataGrid = Convert.ToString(DataGridViewCompteMois.Rows[i].Cells[0].Value);
String IdCompteValue = "select IdCom from Compte where NomCom='" + NomCompteDataGrid + "'";
comm = new SqlCommand(IdCompteValue, conn);
int IdComValue = Convert.ToInt32(comm.ExecuteScalar());
conn.Close();
using (SqlConnection con = new SqlConnection(connstring))
{
using (SqlCommand cmd = new SqlCommand("select SUM( Depense + Recette ) from Tresorerie where IdCom=#IdCom and MONTH(DateTre) = #MONTH AND YEAR(DateTre) = #YEAR GROUP BY IdCom", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#IdCom", IdComValue);
cmd.Parameters.AddWithValue("#MONTH", month);
cmd.Parameters.AddWithValue("#YEAR", year);
con.Open();
total = Convert.ToString(cmd.ExecuteScalar());
con.Close();
}
}
DataGridViewCompteMois.Rows[i].Cells["Total"].Value = total;
//MessageBox.Show(total.ToString());
}
}
Update Solution: look I have a problem which cell selected, this code works
private void CompteMoisdateTimePicker_ValueChanged(object sender, EventArgs e)
{
string month = CompteMoisdateTimePicker.Value.Month.ToString();
string year = CompteMoisdateTimePicker.Value.Year.ToString();
for (int i = 0; i < DataGridViewCompteMois.Rows.Count; i++)
{
conn = new SqlConnection(connstring);
conn.Open();
String NomCompteDataGrid = Convert.ToString(DataGridViewCompteMois.Rows[i].Cells[1].Value);
String IdCompteValue = "select IdCom from Compte where NomCom='" + NomCompteDataGrid + "'";
comm = new SqlCommand(IdCompteValue, conn);
int IdComValue = Convert.ToInt32(comm.ExecuteScalar());
conn.Close();
using (SqlConnection con = new SqlConnection(connstring))
{
using (SqlCommand cmd = new SqlCommand("select SUM( Depense + Recette ) from Tresorerie where IdCom=#IdCom and MONTH(DateTre) = #MONTH AND YEAR(DateTre) = #YEAR GROUP BY IdCom", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#IdCom", IdComValue);
cmd.Parameters.AddWithValue("#MONTH", month);
cmd.Parameters.AddWithValue("#YEAR", year);
con.Open();
//MessageBox.Show(Convert.ToString(cmd.ExecuteScalar()));
DataGridViewCompteMois.Rows[i].Cells["Total"].Value = Convert.ToString(cmd.ExecuteScalar());
con.Close();
}
}
}
}
I think the problem is using ExecuteNonQuery with a SELECT statement since;
For UPDATE, INSERT, and DELETE statements, the return value is the
number of rows affected by the command. When a trigger exists on a
table being inserted or updated, the return value includes the number
of rows affected by both the insert or update operation and the number
of rows affected by the trigger or triggers. For all other types of
statements, the return value is -1.
Looks like you need to use ExecuteScalar as well to get total of your Recette + Depense columns.
I achieved search through one dropdown menu.
private void search_Click(object sender, EventArgs e)
{
string query = "SELECT * FROM magzines where issue_number = '"+comboBox1.Text+"'";
SqlDataAdapter sda = new SqlDataAdapter(query , con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item[0].ToString();
dataGridView1.Rows[n].Cells[1].Value = item[1].ToString();
dataGridView1.Rows[n].Cells[2].Value = item[2].ToString();
dataGridView1.Rows[n].Cells[3].Value = item[3].ToString();
}
}
please help me how i can search through two dropdown menu?
You should change to paramertised query to avoid SQL injection attacks, and not concatenate the SQL string as you're doing. To answer the question, add a second dropdown and use BETWEEN in the query...
string query = "SELECT * FROM magzines where issue_number BETWEEN '"+comboBox1.Text+"' AND '"+comboBox2.Text+"'";
Example using params...
using (SqlConnection conn = new SqlConnection(con))
{
string query = "SELECT * FROM magzines where issue_number BETWEEN '#comboOne' AND '#comboTwo'";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("comboOne", SqlDbType.VarChar).Value = comboBox1.Text;
cmd.Parameters.Add("comboTwo", SqlDbType.VarChar).Value = comboBox2.Text;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
da.Fill(table);
}
}
you can use BindingSource
BindingSource source1 = new BindingSource();
source1.DataSource = view1;
// Set the data source for the DataGridView.
datagridview1.DataSource = dt ;
//The Filter string can include Boolean expressions.
source1.Filter = "artist = 'Dave Matthews' OR cd = 'Tigerlily'";
for more visit http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.filter%28VS.90%29.aspx
I am writing to request some help on my c# syntax. I keep getting syntax in "sda.Fill(dt);" and I can not figure out the reason why.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select distinct Price_type from Price";
DataTable dt = GetData(query);
ddlPrice.DataSource = dt;
ddlPrice.DataTextField = "Price_type";
ddlPrice.DataValueField = "Price_type";
ddlPrice.DataBind();
ddlPrice2.DataSource = dt;
ddlPrice2.DataTextField = "Price_type";
ddlPrice2.DataValueField = "Price_type";
ddlPrice2.DataBind();
ddlPrice2.Items[1].Selected = true;
}
}
protected void Compare(object sender, EventArgs e)
{
string query = string.Format("select price, date from Price where Price_type = '{0}' order by date)", ddlPrice.SelectedItem.Value);
DataTable dt = GetData(query);
string[] x = new string[dt.Rows.Count];
decimal[] y = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
LineChart1.Series.Add(new AjaxControlToolkit.LineChartSeries { Name = ddlPrice.SelectedItem.Value, Data = y });
query = string.Format("select price, date from Price where Price_type = '{0}' order by date)", ddlPrice2.SelectedItem.Value);
dt = GetData(query);
y = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
LineChart1.Series.Add(new AjaxControlToolkit.LineChartSeries { Name = ddlPrice2.SelectedItem.Value, Data = y });
LineChart1.CategoriesAxis = string.Join(",", x);
LineChart1.ChartTitle = string.Format("{0} and {1} Order Distribution", ddlPrice.SelectedItem.Value, ddlPrice2.SelectedItem.Value);
LineChart1.Visible = true;
}
private static DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["bwic testConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
date might be a reserved keyword, depending of the version you use. Write [date] instead. And this
"select price, date from Price where Price_type = '{0}' order by date)"
should be
"select price, date from Price where Price_type = '{0}' order by date"
You can try with this code
using (var con = new SqlConnection(constr))
{
using (var cmd = new SqlCommand(query))
{
using (var sda = new SqlDataAdapter())
{
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
There's nothing syntactically wrong with your GetData() method as shown in your original post. You might try commenting out the entire body of the method and then start uncommenting things one at a time to isolate the actual problem.
But it apparently seems that you don't have a syntax error: you have invalid SQL. The SQL you are trying to execute is:
select price, date from Price where Price_type = '{0}' order by date)
It has two things wrong with it:
The closing (right) parenthesis at the end is your syntax error, and
the parameter should not be enclosed in quotes.
Your SQL should look something like
select price, date from Price where Price_type = {0} order by date
Your method should look something like this:
private static DataTable GetData1( string query , string p0 )
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["bwic testConnectionString"].ConnectionString;
using ( SqlConnection con = new SqlConnection( constr ) )
using ( SqlCommand cmd = con.CreateCommand() )
using ( SqlDataAdapter sda = new SqlDataAdapter(cmd) )
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
SqlParameter p = new SqlParameter() ;
p.Value = p0Value ;
cmd.Parameters.Add( p ) ;
con.Open();
sda.Fill( dt );
con.Close();
}
return dt;
}
Don't forget to use brackets twice - in SELECT clause and in ORDER BY clause too.
in your code bolck as below
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
change it to
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
The problem here is that you havent opened any connection before filling.
You haven't opened a connection anywhere. You must open the connection before you can use it.
If your whole class code is really this, you are missing a closing } at the end of the file for the
public partial class Default2 : System.Web.UI.Page
{
declaration.