Not able to fetch data in asp.net c# - c#

protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\ExportPagetoPDFinASP.Net\App_Data\abcc.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM cookbook";
cmd.Connection = con;
cmd.ExecuteReader();
}
Not able to fetch data. i don't know what is wrong.

ExecuteReader would return you a DataReader, you need to iterate it and get rows from your command.
You can also use a DataTable to fill the rows from DataReader like:
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
You can have the following code:
using (SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\ExportPagetoPDFinASP.Net\App_Data\abcc.mdf;Integrated Security=True;User Instance=True"))
{
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT * FROM cookbook";
cmd.Connection = con;
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
}
}
Consider using using statement with your Connection and Command objects.
You can iterate rows returned from DataReader like:
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0])); //prints first column
}

public string Log(int userResult)
{
string result = "result saved";
using (var conn = new SqlConnection("Data Source=XXXX;InitialCatalog=XXXX;Integrated Security=True"))
{
using (var cmd = new SqlCommand())
{
cmd.CommandText = "dbo.setCalculatorResult";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("RESULT", userResult);
if (conn.State != ConnectionState.Open)
conn.Open();
int rowCount = cmd.ExecuteNonQuery();
if (rowCount == 0)
result = "there was an error";
}
}
return result;
}
and also consider using procs

Related

ToString argument is wrong

I would like to get some help : I can't get values form SQL Database to WPF textbox.
I tried by myself many codes that didn't worked, and this one looks fine but ".ToString" argument is wrong.
What should i put instead ?
using (SqlConnection con = new SqlConnection(MyConnString))
{
SqlCommand sqlCmd = new SqlCommand("SELECT DATE_A FROM Donnees_Accueil", con);
con.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
hourA.Text = sqlReader["Date_A"].ToString;
}
sqlReader.Close();
}
Thank you in advance,
Zancrew.
Well, ToString() is a method, not property, that's why () is required; if you want to concat all the records:
using (SqlConnection con = new SqlConnection(MyConnString))
{
con.Open();
using (SqlCommand sqlCmd = new SqlCommand("SELECT DATE_A FROM Donnees_Accueil", con))
{
using (SqlDataReader sqlReader = sqlCmd.ExecuteReader())
{
StringBuilder sb = new StringBuilder();
while (sqlReader.Read())
{
sb.Append(Convert.ToString(sqlReader["Date_A"]));
}
hourA.Text = sb.ToString();
}
}
}
If you want to get the 1st record only:
using (SqlConnection con = new SqlConnection(MyConnString))
{
con.Open();
using (SqlCommand sqlCmd = new SqlCommand("SELECT DATE_A FROM Donnees_Accueil", con))
{
using (SqlDataReader sqlReader = sqlCmd.ExecuteReader())
{
if (sqlReader.Read())
hourA.Text = Convert.ToString(sqlReader["Date_A"]);
else
hourA.Text = "";
}
}
}

ExecuteNonQuery: Connection property has not been initialized. c sharo

may be i am tired but any body can say what is the poblem?
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='c:\users\deltagare\documents\visual studio 2015\Projects\School\School\school.mdf';Integrated Security=True");
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'schoolDataSet.student' table. You can move, or remove it, as needed.
//this.studentTableAdapter.Fill(this.schoolDataSet.student);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from student";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
student = new StudentController();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
studentGridView.DataSource = dt;
conn.Close();
}
You have either to use the SqlCommand(string,SqlConnection) overload, or set the SqlCommand.Connection property:
SqlCommand cmd = new SqlCommand("select * from student",conn);
Or
cmd.Connection=conn;
you have to assign the connection to the command before you execute it:
cmd.Connection = conn

Jut get as result: System.Data.SqlClient.SqlDataReader

Can someone help me out?
I just get as result tb_localidade: System.Data.SqlClient.SqlDataReader
Why? Here is the code:
private void btn_normalizar_Click(object sender, EventArgs e)
{
//connection string - one or other doenst work
//SqlConnection conn = new SqlConnection("DataSource=FRANCISCO_GP;Initial Catalog=Normalizacao;Integrated Security=True;");
SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString);
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader leitor = cmd.ExecuteReader();
tb_localidade.Text = leitor.ToString();
conn.Close();
}
You can do this by calling Read() on your data reader and assigning the results:
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlDataReader leitor = cmd.ExecuteReader();
while (leitor.Read())
{
tb_localidade.Text = leitor["ART_DESIG"].ToString();
}
}
}
}
Another note is that using a using block for your SqlConnection and SqlCommand objects is a good habit to get into.
Note: this is assigning the result to the tb_localidade.Text for every row in the resultset. If you are only intending for this to be one record, you might want to look into .ExecuteScalar() instead (see below).
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
tb_localidade.Text = cmd.ExecuteScalar().ToString();
}
}
}
before execute "executeReader()" then you must read to get results.
Improvement on Siyual's response. You're only looking for a single result, and this explicitly disposes both the connection and the datareader.
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using(SqlCommand cmd = new SqlCommand(sql, conn)) {
using(SqlDataReader leitor = cmd.ExecuteReader())
{
if (leitor.Read())
{
tb_localidade.Text = leitor["ART_DESIG"].ToString();
}
}
}
}
}
you should just this
SqlDataReader leitor = cmd.ExecuteReader();
string res="";
while(leitor.Read())
{
res=leitor.GetValue(0).ToString()///////if in sql it is varchar or nvarshar
}
tb_localidade.Text = res;
actully datareader is a 1d table and we can access to this with GetValue or GetInt32 or ...

Error :System.NullReferenceException: Object reference not set to an instance of an object

I am trying to debug the above error. Below is my code.
private SqlConnection SQLConn(string name)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings[name].ConnectionString;
return conn;
}
protected void rb2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn = SQLConn("Plastics");
try
{
string selectSQL = "SELECT [Description], [Code], [Change] FROM [plastics]";
SqlCommand cmd = new SqlCommand(selectSQL, conn);
conn.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
catch (SqlException Exception)
{
// catch exception
Response.Write("An error occured");
}
finally
{
conn.Close();
}
}
I get an error on GridView1.DataSource = cmd.ExecuteReader();
What must I instantiate?
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
ds.Tables.Add(dt);
string str = "User ID=username;Password=password;Data Source=Test";
SqlConnection conn = new SqlConnection(str);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from table_name";
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if(dt!=null)
{
GridView2.DataSource = dt;
GridView2.DataBind();
}
}

How to bind a datasource to a label control

It's easy to bind a data source to something like a gridview or repeater, but how would I do it with a label? Heres the sql connection that I want to modify. By the way, I don't need 2 way binding.
public void Sql_Connection(string queryString)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand(queryString, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
The query I'm using:
SELECT Description FROM RbSpecials WHERE Active=1
public string SqlConnection(string queryString)
{
using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = queryString;
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// This will return the first result
// but there might be other
return reader.GetString(0);
}
}
return null;
}
}
This will also ensure that in case of exception all disposable objects are disposed and will properly return the SQLConnection to the connection pool in order to be reused.
And finally assign the Text property of the label:
lblTest.Text = SqlConnection("SELECT Description FROM RbSpecials WHERE Active=1");
use ExecuteReader rather than ExecuteNonQuery
public void Sql_Connection(string queryString)
{
using(SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings"RBConnectionString"].ConnectionString))
{
using(SqlCommand cmd = new SqlCommand(queryString, conn))
{
conn.Open();
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
lblDescription.Text = rdr.GetString(0);
}
}
}
}
}
using (SqlConnection con = new SqlConnection(Connection_String))
{
SqlCommand cmd = new SqlCommand("select * from Customers", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader adpt = cmd.ExecureReader();
if(rdr.Read())
{
lblName.Text = rdr[0].ToString();
}
}

Categories