-1

I'm new to C# and trying to show data from Mysql database to ListView, but keep on failing.

by these coding i didnt get any error but no data showing at the listview when i run the program.

Please advice and help, thanks

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace sql_to_listview
{
public partial class Form1 : Form
{
    MySqlConnection cn = new MySqlConnection("Data Source=localhost;Initial 
    Catalog=rfiddb;uid=username;pwd=password;");
    MySqlCommand cmd = new MySqlCommand();
    MySqlDataReader dr;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        cn.Open();
        cmd.CommandText = "select * from data";
        cmd.Connection = cn;
        dr = cmd.ExecuteReader();

        while(dr.Read())
        {
            ListViewItem lv = new ListViewItem(dr[0].ToString());
            lv.SubItems.Add(dr[1].ToString());
            lv.SubItems.Add(dr[2].ToString());
            lv.SubItems.Add(dr[3].ToString());
            listView1.Items.Add(lv);
        }
        cn.Close();
    }
  }
}

Here is the data table looks like enter image description here

NDSAC
  • 13
  • 1
  • 5
  • Did you spell the table correctly? i.e. is the table "Data" and not "data" – CAMD_3441 Aug 29 '18 at 01:57
  • data is correct – NDSAC Aug 29 '18 at 01:59
  • "but keep on failing". That is a wholly inadequate explanation. You need to use your words and explain what actually happens. If there's an exception thrown, tell us that and provide the error message. Have you actually debugged you code? If not do so now. ALWAYS debug before posting here. Does the `Read` call return `false` on the first go? If so then that means that your query result is empty, plain and simple. That's not even failing. If you tipped up an empty bucket and nothing came out, would that be a failure? – jmcilhinney Aug 29 '18 at 02:06
  • I'm just following a youtube tutorial, and even i run the program there is no error message shown , how do i debug with no error??? and im only trying to do one thing at a time , is that not plain and simple enough ? "select * from tablename" is not plain and simple enough ?? – NDSAC Aug 29 '18 at 02:13
  • bugs and errors are 2 different things – Ňɏssa Pøngjǣrdenlarp Aug 29 '18 at 03:46

2 Answers2

2

I believe this is what you want to achieve.

enter image description here

If yes, you are required to set ListView's View property to Details and add Columns to the ListView.

Here is the code you should use:

    listView1.Columns.Clear(); // Clear previously added columns
    listView1.Items.Clear(); // Clear previously populated items
    listView1.View = View.Details; // Set View property

    // Set Columns
    listView1.Columns.Add("Id"); 
    listView1.Columns.Add("Name");
    listView1.Columns.Add("Number");
    listView1.Columns.Add("Date");

    while(dr.Read())
    {
        ListViewItem lv = new ListViewItem(dr[0].ToString());
        lv.SubItems.Add(dr[1].ToString());
        lv.SubItems.Add(dr[2].ToString());
        lv.SubItems.Add(dr[3].ToString());
        listView1.Items.Add(lv);
    }

Update after looking at the code

Replace your form_load method with this one. Once you understand what has to be done, replace the sample data with MySql code.

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    //cn.Open();  
    //cmd.CommandText = "select * from data";
    //cmd.Connection = cn;
    //dr = cmd.ExecuteReader();

    //listView1.Columns.Clear(); // Clear previously added columns
    //listView1.Items.Clear(); // Clear previously populated items
    //listView1.View = View.Details; // Set View property

    //// Set Columns
    //listView1.Columns.Add("Id");
    //listView1.Columns.Add("Name");           
    //listView1.Columns.Add("Number");
    //listView1.Columns.Add("Date");

    //while (dr.Read())
    //{
    //    ListViewItem lv = new ListViewItem(dr[0].ToString());
    //    lv.SubItems.Add(dr[1].ToString());
    //    lv.SubItems.Add(dr[2].ToString());
    //    lv.SubItems.Add(dr[3].ToString());
    //    listView1.Items.Add(lv);
    //}
    //cn.Close();

    List<List<string>> data = new List<List<string>>();
    var row = new List<string>();
    row.Add("1");
    row.Add("Name");
    row.Add("111");
    row.Add(DateTime.Now.AddDays(-2).ToString());
    data.Add(row);

    row = new List<string>();
    row.Add("2");
    row.Add("Name");
    row.Add("222");
    row.Add(DateTime.Now.AddDays(-2).AddMinutes(-5).ToString());
    data.Add(row);

    row = new List<string>();
    row.Add("3");
    row.Add("Name");
    row.Add("333");
    row.Add(DateTime.Now.AddDays(-2).AddMinutes(-10).ToString());
    data.Add(row);

    //lv = new ListView();
    listView1.Columns.Clear();
    listView1.Items.Clear();
    listView1.View = View.Details;
    listView1.Columns.Add("Id");
    listView1.Columns.Add("Name2");
    listView1.Columns.Add("Number");
    listView1.Columns.Add("Date");
    foreach (var dr in data)
    {
        ListViewItem lv = new ListViewItem(dr[0].ToString());
        lv.SubItems.Add(dr[1].ToString());
        lv.SubItems.Add(dr[2].ToString());
        lv.SubItems.Add(dr[3].ToString());
        listView1.Items.Add(lv);
    }
}
dj079
  • 1,389
  • 8
  • 14
  • Yes, it exactly what i want I have add columns when i add the Listview and click into the little arrow at the top right corner , is that not the same?? And i have pasted your code already ,but it still not result . And its look a bit different – NDSAC Aug 29 '18 at 03:52
  • You missed out setting the View property I believe. – dj079 Aug 29 '18 at 03:53
  • I just need to add those listview1.Columns.clear();..... and listview!.columns.add("xx"); on top of my while(dr.Read()) right ??? And i have set those columns by clicking the top right arrow and view set as details, will that duplicated ?? – NDSAC Aug 29 '18 at 04:18
  • If you have added columns and have set view to details using visual properties by clicking top right arrow, you don’t need to do it again using code. – dj079 Aug 29 '18 at 04:40
  • so will it be myconnection problem ? Is there anyway i can test it ? MySqlConnection("Data Source=localhost;Initial Catalog=rfiddb;uid=username;pwd=password;"); – NDSAC Aug 29 '18 at 06:25
  • No.. as long as you are able to retrieve data from MySql and see the same in the reader. It's not the DB problem. Just copy and replace the part of code I have posted and try. It will work. – dj079 Aug 29 '18 at 06:33
  • i pasted your code and manually removed the columns with visual properties by clicking top right arrow, but still not working...... – NDSAC Aug 29 '18 at 08:26
  • try this link can did it work !!! Thank You so much https://drive.google.com/drive/folders/1KmEXH0WLblTWJRknywM2jL4VKA70FD36?usp=sharing – NDSAC Aug 29 '18 at 09:36
  • I understand you have make a "data" table by "List> data = new List>();" Right? and listView just showing the data what you added in the "data" table. I could able to show the data you add right now .and the columns u cleared and added, so the listview is working. now how do i confirm the sql connection ? – NDSAC Aug 30 '18 at 01:43
  • BTW thank you for your time and patience on helping me, i know this is something really simple. Im really appreciated. – NDSAC Aug 30 '18 at 01:45
  • The List> simply imitates data retrieved from your DB. Parent List is your “dr” in commented code and the child List is each row in that “dr”. You just need to populate the “dr” from your DB and use rows in “dr” within the loop. – dj079 Aug 30 '18 at 01:50
0

By any chance, do you try something like this before ?

https://stackoverflow.com/a/4018147/5209563

using(SqlDataReader rdr = cmd.ExecuteReader())
{
    while (rdr.Read())
    {
        var myString = rdr.GetString(0); //The 0 stands for "the 0'th column", so the first column of the result.
        // Do somthing with this rows string, for example to put them in to a list
        listDeclaredElsewhere.Add(myString);
    }
}
Kira Hao
  • 1,077
  • 11
  • 17
  • Sorry i have no idea what this is, Im new to C# and just trying out a tutorial from youtube. Can you explain what this is or is there any web site i could learn about it ? Thanks – NDSAC Aug 29 '18 at 02:17
  • this code actually rewrite what you have into `using()`, in C# we call it using statement. Normally for a connection establish. So in this code, credit from the answer post, it try to establish connection with data reader then read it. Once it done. the `rdr` will be dipose, mean remove from memory. – Kira Hao Aug 29 '18 at 02:22