Jama Dharma
Jama Dharma

Reputation: 7

Read from SQL to textblock

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.

Upvotes: 0

Views: 305

Answers (2)

Saeed Amiri
Saeed Amiri

Reputation: 22565

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

Upvotes: 0

GrayFox374
GrayFox374

Reputation: 1782

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

Upvotes: 1

Related Questions