Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read and print out data from mysql in c#

Tags:

c#

mysql

My problem is that I can't print out all the data from the table in my mysql database, I got out just last row in the given table "teacher". is there anyone who can help me find the error?

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

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

        private void button1_Click(object sender, EventArgs e)
        {
            string sql = " SELECT * FROM teacher  ";
            MySqlConnection con = new MySqlConnection("host=localhost;user=root;password=859694;database=projekt;");
            MySqlCommand cmd = new MySqlCommand(sql, con);

            con.Open();

           MySqlDataReader  reader = cmd.ExecuteReader();

           while (reader.Read()) {
               data2txt.Text = reader.GetString("id");
              datatxt.Text = reader.GetString("userId");
           }

        }

        private void btnclose_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
like image 597
Bahaa Ashi Avatar asked Sep 13 '12 14:09

Bahaa Ashi


2 Answers

Obviously your code shows the last row values of teacher table into your text fields on form.Because your are looping throught the datareader and assigning the values to textfiled.So each iteration it will overwright the previous values in textbox.

like image 36
AnandPhadke Avatar answered Oct 01 '22 13:10

AnandPhadke


Your problem is that you are overwriting data2txt.Text and datatxt.Text on each row of data. if you want to see all of the data in those fields, something like this should do what you need:

data2txt.Text = string.Empty;
datatxt.Text = string.Empty;

while (reader.Read())
{
    data2txt.Text += $"{reader.GetString("id")};";
    datatxt.Text += $"{reader.GetString("userId")};";
}
like image 120
Mike Corcoran Avatar answered Oct 01 '22 14:10

Mike Corcoran