1

First off this is my first attempt at C#. My issue is, regardless of me using datatables, lists, or mysqldatareader; the query only returns one result and only the last result of the table.

My Table Values are(Col names first): Index City 1 Paris 2 London

My C# last code attempt was:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace MySQL_Sample
{

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }


    private void button1_Click(object sender, EventArgs e)
    {
        //MySql connections
        MySqlConnection connection;
        string host;
        string db;
        string uid;
        string pass;
        host = "localhost";
        db = "sample";
        uid = "root";
        pass = "";
        string ConnectionString = "SERVER=" + host + ";" + "DATABASE=" + db + ";" + "UID=" + uid + ";" + "PASSWORD=" + pass + ";";
        connection = new MySqlConnection(ConnectionString);
        connection.Open();
        //MySql Commands
        string sql = "SELECT * FROM table1";
        MySqlCommand cmd = new MySqlCommand(sql, connection);
        MySqlDataReader rdr = cmd.ExecuteReader();
        //MySql Call back
        while(rdr.Read())
        {
            DataTxtBox.Text = rdr[0].ToString() + " | " + rdr[1].ToString();
        }
    }

 }
}

1 Answer 1

4

You get all the records one by one but the line :

DataTxtBox.Text = rdr[0].ToString() + " | " + rdr[1].ToString();

has an assignment that gets only current record. Instead try this:

DataTxtBox.Text += rdr[0].ToString() + " | " + rdr[1].ToString();

The important bit is the +=. This means that the rows get appended instead of overwriting the previous value.

Sign up to request clarification or add additional context in comments.

1 Comment

This was perfect; also note that DataTxtBox.Text += rdr[0].ToString() + " | " + rdr[1].ToString(); was changed to: DataTxtBox.Text += rdr[0].ToString() + " | " + rdr[1].ToString()+"\r\n";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.