我是C#的新手,正试图将Mysql数据库中的数据显示到ListView,但仍然失败。
通过这些编码,运行程序时我没有收到任何错误,但没有数据显示在列表视图中。
请咨询和帮助,谢谢
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();
}
}
}
这是数据表的样子
答案 0 :(得分:1)
我相信这是您想要实现的目标。
如果是,则需要将ListView
的{{1}}属性设置为View
并将Details
添加到Columns
。
这是您应该使用的代码:
ListView
查看代码后进行更新
用此方法替换form_load方法。一旦了解了必须执行的操作,就将示例数据替换为MySql代码。
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);
}
答案 1 :(得分:0)
如果有机会,您之前尝试过这种方法吗?
https://stackoverflow.com/a/4018147/5209563
<template name="alljobs">
<h3 class="notranslate">Jobs that you can help with</h3>
<ul>
{{#each jobs}}
{{> postedjob}}
{{/each}}
</ul>
</template>
<!-- template Description - called by alljobs to fill in list of jobs to sign up for-->
<template name="postedjob">
<span class="ShortDesc"><a data-class="linked-name" href=/SignUp/{{_id}}>
<span class="notranslate">{{ShortDesc}}</span></a>
</span>
<li>{{LongDesc}}</li>
</template>
------
Template.alljobs.helpers({
jobs() {
return db.Jobs.aggregate([{
$lookup: {
from: "helperjobs",
localField: "_id",
foreignField: "job",
as: "temp"
}},
{
$match: { "temp.HelperName": { $exists: false } }
}
])
},
});