How to display data from SqlCommand in other languages - c#

I have this very short code, and while trying to display data from the database that no all the data is in English, I'm getting in the cmd ???? instead of the actual data. How can I solve this?
SqlConnection conn = new SqlConnection("Data Source = ron\\SQLEXPRESS; Initial Catalog = Cafeteria; Integrated Security = True");
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("select * from [Product]", conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0].ToString());
}
}
finally
{
if (rdr != null)
{
rdr.Close();
}
if (conn != null)
{
conn.Close();
}
}

Related

C# - Access Database: Why SELECT * FROM table is not working?

A simple "select * from tablename" sql query works for a table named 'mode' but not for a table named 'user'. Why?
Both tables have 2 columns. If I run the program with the "mySQL" variable as "SELECT * FROM mode" it works fine. If I put the user table instead, which means the mySQL would have been "SELECT * FROM user" then it raises an exception which says "Syntax error in FROM clause.". How can this be?
Here is the code:
static void Main(string[] args)
{
String connectionstring = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Accounts.mdb";
OleDbConnection conn;
conn = new OleDbConnection(connectionstring);
try
{
conn.Open();
}
catch (Exception)
{
Console.Write("Could not connect to database");
}
String mySQL = "SELECT * FROM user";
OleDbCommand cmd = new OleDbCommand(mySQL, conn);
OleDbDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.Write(String.Format("{0}\n,{1}\n", rdr.GetValue(0).ToString(), rdr.GetValue(1).ToString()));
}
Console.Read();
}
Because USER is a reserved word in MS-Access
Change you query to encapsulate it between square brakets
SELECT * FROM [User]
albeit I suggest you to change the name of the table
Do like Steve said. And a suggestion for your code:
String connectionstring = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Accounts.mdb";
OleDbConnection conn = null;
OleDbCommand cmd = null;
OleDbDataReader rdr = null;
String mySQL = "SELECT * FROM [user]";
try
{
conn = new OleDbConnection(connectionstring);
conn.Open();
cmd = new OleDbCommand(mySQL, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.Write(String.Format("{0}\n,{1}\n", rdr.GetValue(0).ToString(), rdr.GetValue(1).ToString()));
}
Console.Read();
conn.Close();
}
catch (Exception ex)
{
Console.Error.Write("Error founded: " + ex.Message);
}
finally
{
if (conn != null) conn.Dispose();
if (cmd != null) cmd.Dispose();
if (rdr != null) rdr.Dispose();
}

Combobox Showing Old Database Values

I retrived values by the use of SqlCommand and SqlReader from column and stored in List<String> and the added to ComboBox(Type:DropDownList) but Eventhough i have deleted Some of this values from database Combobox is still showing it.
I am clearing items befor allocating by
mycombobox.Items.Clear();
It looks as it is not affected by values I retrive every time when the Form gets Loaded.
SqlDataReader rdr1 = null;
SqlConnection con1 = null;
SqlCommand cmd1 = null;
try
{
List<string> namesCollection=new List<string>();
// Open connection to the database
string ConnectionString = #"Data Source=MyPC-PC\SQLEXPRESS;Initial Catalog=DryDB;Integrated Security=True";
con1 = new SqlConnection(ConnectionString);
con1.Open();
cmd1 = new SqlCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT PName from MASTER order by PName";
cmd1.Connection = con1;
rdr1 = cmd1.ExecuteReader();
namesCollection.Add("Select");
if (rdr1.Read()==true)
{
do
{
namesCollection.Add("" + rdr1[0].ToString());
} while (rdr1.Read()) ;
}
else
{
}
foreach(string pname in namesCollection)
cb.Items.Add(pname);
namesCollection.Clear();
cb.SelectedIndex =0;
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
if (rdr1 != null)
rdr1.Close();
if (con1.State == ConnectionState.Open)
con1.Close();
}
Thanks in advance.
Use the DataSource property of the Combobox instead of the adding the items one by one. So your code will be something like the following:
SqlDataReader rdr1 = null;
SqlConnection con1 = null;
SqlCommand cmd1 = null;
try
{
List<string> namesCollection = new List<string>();
// Open connection to the database
string ConnectionString = #"Data Source=MyPC-PC\SQLEXPRESS;Initial Catalog=DryDB;Integrated Security=True";
con1 = new SqlConnection(ConnectionString);
con1.Open();
cmd1 = new SqlCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT PName from MASTER order by PName";
cmd1.Connection = con1;
rdr1 = cmd1.ExecuteReader();
namesCollection.Add("Select");
if (rdr1.Read()==true)
{
do
{
namesCollection.Add("" + rdr1[0].ToString());
} while (rdr1.Read()) ;
}
else
{
}
//Replace this part...
//foreach(string pname in namesCollection)
//cb.Items.Add(pname);
//With this...
cb.DataSource = namesCollection;
cb.SelectedIndex =0;
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
if (rdr1 != null)
rdr1.Close();
if (con1.State == ConnectionState.Open)
con1.Close();
}
There is a similar question here
Hope this helps
Let's say the code to populate the ComboBox is placed in the populate_cb() method
private void populate_cb(){
cb.Items.Clear();
SqlDataReader rdr1 = null;
SqlConnection con1 = null;
SqlCommand cmd1 = null;
try
{
// Open connection to the database
string ConnectionString = #"Data Source=MyPC-PC\SQLEXPRESS;Initial Catalog=DryDB;Integrated Security=True";
con1 = new SqlConnection(ConnectionString);
con1.Open();
cmd1 = new SqlCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT PName from MASTER order by PName";
cmd1.Connection = con1;
rdr1 = cmd1.ExecuteReader();
cb.Items.Add("Select");
while(rdr1.Read())
{
cb.Items.Add(rdr1[0].ToString());
}
cb.SelectedIndex =0;
con1.Close();
}
catch(Exception ex){
// handle exception
}
}//end of populate_cb()
Call populate_cb() method form form_load() and
Call from the place after the deletion process
You need to make sure your deletion process really deletes the records from database!

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

Problem with usage of multiple DataReaders in ASP.NET(C#)

SqlConnection conn1 = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand COMM = new SqlCommand("select Role from Login where User_Name='admin'", conn1);
conn1.Open();
SqlDataReader reader = COMM.ExecuteReader();
while (reader.Read())
{
string s = reader["Role"].ToString();
}
reader.Close();
conn1.Close();
SqlConnection conn = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand comm = new SqlCommand("Select * from FileUpload where UploadedBy='"+NAME+"'",conn);
try
{
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
if (s.Equals("admin"))
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
if(s.Equals("teacher"))
{
GridView2.DataSource = rdr;
GridView2.DataBind();
}
rdr.Close();
//reader.Close();
}
catch
{
conn.Close();
}
I'm getting error in the below connection saying s does not exist in the current context. How to use the multiple datareaders please help me.
Declare string s out of hte loop
string s;
while (reader.Read())
{
s = reader["Role"].ToString();
}
SqlConnection conn1 = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand COMM = new SqlCommand("select Role from Login where User_Name='admin'", conn1);
conn1.Open();
SqlDataReader reader = COMM.ExecuteReader();
string s = String.Empty;
while (reader.Read())
s = reader["Role"].ToString();

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