【问题标题】:Data from datatable only populating one column in ListView with C# Winforms数据表中的数据仅使用 C# Winforms 填充 ListView 中的一列
【发布时间】:2014-03-20 04:08:15
【问题描述】:

我有一个从 Access 数据库中填充的数据表,该数据库具有表名、“代码”和 3 列“CodeNum”、“TableName”和“Desc”。在我的 Winforms C# 应用程序中,我想用这个数据表填充一个 ListView 并让它以相同的格式显示列(带有列名)。我尝试了许多代码组合,但无法使其正常工作。下面的代码在第一列中显示 CodeNum 和 TableName 数据,而不是 DESC 数据,并且不显示列名(CodeNum)。非常感谢任何帮助。真的不需要 "DataRowState.Deleted" if 语句,但在注释掉时工作方式相同。

Listview 应该有 3 列,每列中都列出了数据。

谢谢。

        //Get data from Access database and populate datatable "dt"
        OleDbConnection Conn = new OleDbConnection();
        string conn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=M:\gendoc\Codes.mdb;Persist Security Info=False;";
        ListViewItem LItem1 = new ListViewItem();
        Conn.ConnectionString = conn;
        Conn.Open();

        DataTable dt = new DataTable();
        DataSet ds = new DataSet();
        ds.Tables.Add(dt);
        OleDbDataAdapter da = new OleDbDataAdapter("select * from Codes order by CodeNum", Conn);
        da.Fill(dt);
        Conn.Close();


        // Clear the ListView control
        listView1.Items.Clear();
        int ColCount = dt.Columns.Count;
        //Add columns
        for (int k = 0; k < ColCount; k++)
        {
            listView1.Columns.Add(dt.Columns[k].ColumnName);
        }
        // Display items in the ListView control
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            DataRow drow = dt.Rows[i];

            // Only row that have not been deleted
            if (drow.RowState != DataRowState.Deleted)
            {
                // Define the list items
                ListViewItem lvi = new ListViewItem(drow[0].ToString());
                for (int j = 1; j < ColCount; j++)
                {
                    string g = drow[j].ToString();
                    lvi.SubItems.Add(drow[j].ToString());
                }
                // Add the list items to the ListView
                listView1.Items.Add(lvi);
            }
        }

【问题讨论】:

  • 您的代码有效。也许也可以打电话给listView1.Columns.Clear(),因为不清楚你在哪里调用这段代码。
  • 感谢 LarsTech 的回复。在主表单加载事件中,我正在显示表单:
  • CodeList CL = new CodeList(); CL.Show();
  • 发布的代码并没有重现问题。我有一个包含三列和几行的 DataTable,ListView 控件使用您的代码正确填充。
  • 数据表是否正确?我检查了一下,它在 ListView 中添加了 3 列。就好像 ListView 无法识别它一样。我尝试过的所有代码变体仅在 1 列中填充数据。我需要用 ListView 指定什么来启用多列吗?感谢您的宝贵时间。

标签: winforms listview datatable


【解决方案1】:

右键列表视图,属性,查看,将选项更改为详细信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多