ToString argument is wrong - c#

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 = "";
}
}
}

Related

Data from SQL reader to datatable - Invalid attempt to call Read when reader is closed

I am keep trying and still don't know how to fix this, keep getting same error. I want to get data from the database to txt file.
using (conn)
{
conn.Open();
SqlCommand cmd = new SqlCommand(command)
cmd.Connection = (SqlConnection)conn;
using (cmd)
{
SqlDataReader reader = cmd.ExecuteReader();
using(reader)
{
while (reader.Read())
{
dt.Load(reader);
}
}
using (StreamWriter sw = new StreamWriter(txtPath.Text + fileName))
{
// write to text file from Datatable dt
} }
Try insted your code, something like this:
DataTable myDataTable = new DataTable();
using (SqlConnection myConnection = new SqlConnection(yourDBconn)
{
yourDBconn.Open();
using (SqlDataAdapter myAdapter = new SqlDataAdapter(strYourQuery, yourDBconn))
{
myAdapter.Fill(myDataTable);
}
}
}
Here you are. Tested.
var customers = new List<Tuple<int, string>>(); // the list of ID, Name
using (var con = new SqlConnection("your connection string"))
{
using(SqlCommand cmd = new SqlCommand("select ID, Name from Customer", con))
{
con.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
customers.Add(new Tuple<int, string>(
(int)reader["ID"], reader["Name"].ToString()));
}
}
}
}
// Store customers to file

How to check whether sql query returning a value or not?

I have a SQL query. Just i want to check query returning a values or not using c#. Can any one help on this to fix it. Thanks in advance.
Sqlcommand cmd = new Sqlcomman("select Name from Engdetails",con)
if (query != 0)
{
some coding..
}
else
{
coding...
}
SqlCommand cmd = new SqlCommand("select Name from Engdetails",con)
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
// The command returns Row(s)
}
else
{
// No Row has been returned.
}
There are a number of ways to work with sqlCommand; some examples:
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
...
or
using (SqlCommand cmd = new SqlCommand(query, connection))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(data);
}
if it has data, the data will be in data.Tables
SqlCommand cmd = new SqlCommand("select Name from Engdetails", con);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
// somecoding
}
else
{
// somecoding
}
a example in this case rdr.GetString is Name value of the query.
using (MySqlConnection conn = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand())
{
MySqlDataReader rdr = null;
string[] dados_bd = new string[2];
conn.Open();
cmd.Connection = conn;
cmd.CommandText = sql;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (estado == 1)
{
dados_bd[0] = rdr.GetString(0);
cmd.ExecuteNonQuery();
For the UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the SQL statement.
For all other types of statements, the return value is -1.

Not able to fetch data in asp.net 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

Calling database using sql and using call in label in C#.

So i have code that can call a string from database that works perfectly for my label but when i try to call an integer it doesn't work. How can i reformat the code below to work for an integer?
string MoneySaved = null;
string sql = "Select Distinct(Tester) From VExecutionGlobalHistory Where Tester = 'strUserName'";
string connString = "myconnectionstringgoeshere";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand(sql, conn))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
MoneySaved = reader[0] as string;
MoneySavedLabel.Text = MoneySaved;
//break for single row or you can continue if you have multiple rows...
break;
}
}
conn.Close();
}
Here is what worked:
string MoneySaved = null;
string sql = "Select Distinct(Tester) From VExecutionGlobalHistory Where Tester = 'strUserName'";
string connString = "myconnectionstringgoeshere";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand(sql, conn))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
MoneySaved = reader[0].ToString();
MoneySavedLabel.Text = MoneySaved;
//break for single row or you can continue if you have multiple rows...
break;
}
}
conn.Close();
}

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