How to bind a datasource to a label control - c#

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();
}
}

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

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

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();
}

Categories