如何将datagridview视图的值放到listview c#

时间:2017-11-12 04:00:32

标签: c# listview datagridview

我有来自DataTable的DataGridView存储数据从SQL数据库获取。这一步没什么错误。但是当我尝试将DataGridView中的所有数据都放入ListView时,它总是说:"附加信息:对象引用未设置为对象的实例。"当运行到代码行时将数据添加到listview。

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

    namespace Sample_SignIn
    {
        public partial class game : Form
        {
            SqlConnection con;
            public game()
            {
                InitializeComponent();
                con = new SqlConnection("Data Source=192.168.100.49;Initial Catalog=Chatlan;User ID=sa;Password=sa2014");
            }

            private void game_Load(object sender, EventArgs e)
            {

                    if (con.State == ConnectionState.Closed)
                    {
                        con.Open();
                    }

                DataTable dtbl = new DataTable();
                String str = "select CauHoi from CauHoi";
                SqlCommand cmd = new SqlCommand(str, con);

                SqlDataAdapter sqldata = new SqlDataAdapter(str, con);

                sqldata.Fill(dtbl);
                dataGridView1.DataSource = dtbl;

                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    foreach (DataGridViewCell cell in row.Cells)
                    {
//This line make an error "Additional information: Object reference not set to an instance of an object"
                        listView1.Items.Add(cell.Value.ToString());
                    }
                }                                              
                if (con.State == ConnectionState.Open)
                    {
                        con.Close();
                        return;
                    }                        
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

如果您正在使用Visual Studio,请在该行上放置一个断点,将鼠标悬停在每个属性上,并检查是否有任何属性为null。

答案 1 :(得分:0)

此问题的解决方案是将DataGridView的AllowUserToAddRows属性设置为false。