本文介绍了如何添加项目在一个DataTable到ListView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个C#Windows窗体应用程序。

I am currently developing a C# Windows Form Application.

现在我想使用一个SQL命令从数据库中获取信息填写,我需要在我的应用程序的信息。

Now I am trying to use a SQL Command to retrieve information from the database to fill in the information that I need to have in my Application.

一个简单的查询是SELECT * FROM位置

A sample query would be "select * from Location"

在位置表中会有像locationId,LOCATIONNAME,districId等等等等变量
我用下面的code

In the Location table there would be variables like locationId, LocationName , districId etc etc.I used the following code

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("connectionstring");
    SqlDataAdapter ada = new SqlDataAdapter("select * from MasterLocation", con);
    DataTable dt = new DataTable();
    ada.Fill(dt);

    for (int i = 0; i < dt.Rows.Count; i++)
    {
        DataRow dr = dt.Rows[i];
        ListViewItem listitem =new ListViewItem(dr["pk_Location_ID"].ToString());
        listitem.SubItems.Add(dr["var_Location_Name"].ToString());
        listitem.SubItems.Add(dr["fk_int_District_ID"].ToString());
        listitem.SubItems.Add(dr["fk_int_Company_ID"].ToString());
       listView1.Items.Add(listitem);
    }

输出是:

但它应该是这样的:

推荐答案

你必须改变一些code

you have to change some code

private void button1_Click(object sender, EventArgs e)
{
    listView1.View = View.Details;
    SqlConnection con = new SqlConnection("connectionstring");
    SqlDataAdapter ada = new SqlDataAdapter("select * from MasterLocation", con);
    DataTable dt = new DataTable();
    ada.Fill(dt);

    for (int i = 0; i < dt.Rows.Count; i++)
    {
        DataRow dr = dt.Rows[i];
        ListViewItem listitem = new ListViewItem(dr["pk_Location_ID"].ToString());
        listitem.SubItems.Add(dr["var_Location_Name"].ToString());
        listitem.SubItems.Add(dr["fk_int_District_ID"].ToString());
        listitem.SubItems.Add(dr["fk_int_Company_ID"].ToString());
       listView1.Items.Add(listitem);
    }

这篇关于如何添加项目在一个DataTable到ListView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 22:58