Read from SQL to textblock - c#

Application — one TextBlock, one Button. + SQL database — one table.
I'm trying to read from sql to textblock, when i click the button, but it does not work.
private void nextButton_Click(object sender, RoutedEventArgs e)
{
GetSqlData();
}
private void GetSqlData()
{
string connectionString = #"Data Source=Jama-Dharma\sqlexpress;Initial Catalog=Cars;Integrated Security=True";
SqlConnection sqlConnection = new SqlConnection(connectionString);
using (sqlConnection)
{
string sqlQuery = #"SELECT c.Name FROM CarsCatalog c";
SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection);
sqlConnection.Open();
SqlDataReader sqlReader = sqlCommand.ExecuteReader();
while (sqlReader.Read())
{
nameTextBlock.Text = sqlReader.GetString(0);
}
sqlConnection.Close();
}
}
How to make that when click on button, obtain the next ID values from SQL.

From a quick glance, it looks like your while loop just overwrites the textblock. Update the textblock text AFTER you exit the loop. Try something like
var sb = new StringBuilder();
while (sqlReader.Read())
{
sb.AppendLine(sqlReader.GetString(0));
}
nameTextBlock.Text = sb.ToString();

You can save last ID you got till now, and get next ID which is greater than this saved id.
e.g:
using (var sqlConnection = new SqlConnection(...))
{
string sqlQuery = #"SELECT c.Name,c.ID FROM CarsCatalog c where c.ID > "
+ lastID.ToString();
SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection);
sqlConnection.Open();
SqlDataReader sqlReader = sqlCommand.ExecuteReader();
if (sqlReader.Read())
{
nameTextBlock.Text = sqlReader.GetString(0);
lastID = sqlReader.GetInt(1);
}
}

Related

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

Deleting Several Rows with a condition

Hello trying to delete several rows of the table according to a condition, however i need some help with it, basically i want to delete all rows, while the condition is true and then stop and leave the rest untouched.
EDIT: Regarding the comments i apologize, im fairly new to programming, sorry if not doing things correctly im new to this website as well.
private void button1_Click(object sender, EventArgs e)
{
string varsql2check = "";
do{
SqlConnection conn = new SqlConnection(#"Data Source=.\wintouch;Initial Catalog=bbl;User ID=sa;Password=Pa$$w0rd");
conn.Open();
string varsql = "DELETE FROM wgcdoccab WHERE 'tipodoc' ='FSS' and 'FP' "; //sql query
SqlCommand cmd = new SqlCommand(varsql, conn);
SqlDataReader dr = cmd.ExecuteReader();
} while(varsql2check = "SELECT * from wgcdoccab where 'tipodoc' !='FSS' and !='FP' and contribuinte !='999999990' and datadoc != CONVERT(varchar(10),(dateadd(dd, -1, getdate())),120);");
dr.Close();
conn.Close();
}
What you need to do is:
private void button1_Click(object sender, EventArgs e)
{
bool check = true;
do
{
string connectionString = #"Data Source=.\wintouch;Initial Catalog=bbl;User ID=sa;Password=Pa$$w0rd";
string queryString = string.Empty;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
queryString = "DELETE FROM wgcdoccab WHERE 'tipodoc' ='FSS' and 'FP' ";
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
queryString = "SELECT * from wgcdoccab where 'tipodoc' !='FSS' and !='FP' and contribuinte !='999999990' and datadoc != CONVERT(varchar(10),(dateadd(dd, -1, getdate())),120)";
using (SqlCommand command = new SqlCommand(queryString, connection))
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
check = true;
}
else
{
check = false;
}
}
}
}
while (check);
}
Generally what I have done by editing your code is:
Add the using statement in order to release the resources from the established connections.
You should be using the returned types from the exeqution of the queries. The ExecuteNonQuery() will return the numbers of rows affected, in our case we are particularly interested in the rows returned from the select statement after the delete query. We create a reader and depending of the number of rows, in our case we are only interested if there are rows or no, branch accoringly. If we get no rows from the select (everything is deleted) we just continue, if we get nothing (reader.HasRows returns false) we repeat the delete query and check again.
Simple as that.

How to fix Error ExecuteReader

Error An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code. How to fix it?
Image: http://i.stack.imgur.com/7Sibc.png
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=QEAG1YU4664IBKF\HUYNHBAO;Initial Catalog=TonghopDB;User ID=sa;Password=koolkool7");
conn.Open();
SqlCommand sc = new SqlCommand("select Title from TongHopDB", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Title", typeof(string));
dt.Load(reader);
cboxDB.ValueMember = "Title";
cboxDB.DisplayMember = "Title";
cboxDB.DataSource = dt;
conn.Close();
}
private void cboxDB_SelectedIndexChanged(object sender, EventArgs e)
{
string sql = "Select Title, Post from TongHopDB where Title = " + cboxDB.SelectedValue.ToString(); // câu query có thể khác với kiểu dữ liệu trong database của bạn
SqlConnection conn = new SqlConnection(#"Data Source=QEAG1YU4664IBKF\HUYNHBAO;Initial Catalog=TonghopDB;User ID=sa;Password=koolkool7");
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader sdr = cmd.ExecuteReader();
textBox1.Text = sdr.GetValue(0).ToString();
textBox2.Text = sdr.GetValue(1).ToString();
sdr.Close();
sdr.Dispose();
conn.Close();
conn.Dispose();
}
string sql = "Select Title, Post from TongHopDB where Title = '" + cboxDB.SelectedValue.ToString()+"'";
However I strongly suggest to use parameters:
string sql = "Select Title, Post from TongHopDB where Title = #Title";
cmd.Paramaters.Add( "#Title",cboxDB.SelectedValue.ToString());
I strongly suspect your Title is character typed, that's why it needs to used with single quotes as;
where Title = '" + cboxDB.SelectedValue.ToString() + "'";
But don't use this way.
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your SqlConnection, SqlCommand and SqlDataReader objects automatically instead of calling Close or Dispose methods manually.
using(var conn = new SqlConnection(#"Data Source=QEAG1YU4664IBKF\HUYNHBAO;Initial Catalog=TonghopDB;User ID=sa;Password=koolkool7"))
using(var cmd = conn.CreateCommand())
{
cmd.CommandText = "Select Title, Post from TongHopDB where Title = #title";
cmd.Parameters.Add("#title", SqlDbType.NVarChar).Value = cboxDB.SelectedValue.ToString();
// I assumed your column type is nvarchar.
conn.Open();
using(SqlDataReader sdr = cmd.ExecuteReader())
{
if(dr.Read())
{
textBox1.Text = sdr.GetValue(0).ToString();
textBox2.Text = sdr.GetValue(1).ToString();
}
}
}
cboxDB.SelectedValue is Apple according to the error shown in your screen shot. Your SQL statement is saying in plain English:
Select Title(column) and Post(column) from TongHopDB(table) where Title(column) equals Apple(column)
Apple is not a valid column!
While it would work to simply add single quotes around the value of cboxDB, you should use parameters instead of concatenating a string. http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/

how to retrieve data from database in combobox c#

I wrote this code but I do not know why this line gives error!
String sname = dr.GetString ("name");
My code:
SqlConnection cn = new SqlConnection(
"Data Source=.;Initial Catalog=logindb;Integrated Security=True");
string query1 = "select * from tbllogin";
SqlCommand cmd = new SqlCommand(query1);
SqlDataReader dr;
try
{
cn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
String sname = dr.GetString("name");
comboBox1.Items.Add(sname);
}
}
catch (Exception e)
{
// do smth about exception
}
First of all you have to check this again:
SqlConnection cn = new SqlConnection(
"Data Source=.;Initial Catalog=logindb;Integrated Security=True");
Data Source=.; This is wrong and it will give you an error.
After that you can use the code below to achieve what you want. The code below also uses using statement to dispose the connection.
using (
SqlConnection connection = new SqlConnection(strCon)) // strCon is the string containing connection string
{
SqlCommand command = new SqlCommand("select * from tbllogin", connection);
connection.Open();
DataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
comboBox1.Items.Add(reader.GetString(int index)); // index of column you want, because this method takes only int
}
}
reader.Close();
}
(Amazingly) GetString only take an index as parameter.
See MSDN
public override string GetString(int i)
With no other signatures :-(
However you could write:
String sname = dr.Item["name"].ToString();
MSDN says that SqlDataReader.GetString method accepts an int as a parameter, which is the index of the column.
What you need is this:
while (dr.Read())
{
String sname = (string)dr["name"];
comboBox1.Items.Add(sname);
}
Here's your code:
SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=logindb;Integrated Security=True");
string query1 = "select * from tbllogin"; SqlCommand cmd = new SqlCommand(query1); SqlDataReader dr;
try {
cn.Open(); dr = cmd.ExecuteReader();
while (dr.Read())
{ String sname = (string)dr["name"];
comboBox1.Items.Add(sname);
}
}
catch (Exception e) { MessageBox.Show(e.Message, "An error occurred!"); }
The catch block wasn't written correctly, you missed the (Exception e) part.

C# Add value to a texbox based on the Combobox selection

We have selected a value from a combobox and need the related information in the textbox.
The following code does not work for the same.
private void itemcode_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = (string)itemcode.SelectedItem;
SqlConnection conn3 = new SqlConnection(connString);
conn3.Open();
//For Redundency Checking Code of Supplier id.
string iname = "select Itemname from Items where Itemcode='" +
itemcode.SelectedItem.ToString() + "'";
SqlCommand cmdRedun1 = new SqlCommand(iname, conn3);
SqlDataReader dr1 = cmdRedun1.ExecuteReader();
dr1.Read();
itemname.Text = dr1["Itemname"].ToString();
dr1.Close();
}
First Check your Item Value Of Combo box , and then create your query with StringFormat
for example :
string iname = String.Format("select Itemname from Items where Itemcode='{0}'",
itemcode.SelectedItem.ToString()) ;
//-- then please check out below code :
SqlConnection SqlConn = new SqlConnection(this.ConnectionString);
SqlConn.Open();
SqlCommand SqlCmd = new SqlCommand(" Your Select....", SqlConn);
SqlCmd.CommandType = CommandType.Text;
SqlDataReader r = SqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
//----need this
while (r.Read())
itemname.Text = string.IsNullOrEmpty(r["Itemname"].ToString()) ?
string.Empty : r["Itemname"].ToString();
r.Close();
if (SqlConn.State != ConnectionState.Closed)
SqlConn.Close();
You can try ExecuteScalar instead of SqlDataReader.

Categories