ListView对象引用未设置为对象的实例

本文关键字:对象 实例 设置 对象引用 ListView | 更新日期: 2023-09-27 18:20:55

我的UserControl出现问题。当我启动程序时,在"listView1.Items.Add(horario);"行中出现了"Object reference not set to a instance of a Object"错误。我真的不知道该怎么办。也许这是一个愚蠢的问题,但我找不到。你能帮我吗?我已经尝试过动态使用ItemsSource和xaml方式,但没有成功。

<UserControl x:Class="Clipboard_final.Horas"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300" Width="1258" Height="596">
<Grid Loaded="Grid_Loaded">
    <Label Content="Horários" Height="61" Name="label1" VerticalAlignment="Top" FontSize="40" Margin="0,-9,1090,0" />
    <Label Content="Cheque ou adicione novos horários realizados" Height="28" HorizontalAlignment="Left" Margin="29,40,0,0" Name="label2" VerticalAlignment="Top" />
    <Label Content="Label" Height="32" Margin="0,85,567,0" Name="label3" VerticalAlignment="Top" FontSize="15" FontStretch="Normal" HorizontalAlignment="Right" Width="520" />
    <Label Content="Entrou" Height="28" HorizontalAlignment="Left" Margin="183,132,0,0" Name="label4" VerticalAlignment="Top" />
    <Label Content="Saiu" Height="28" HorizontalAlignment="Left" Margin="188,166,0,0" Name="label5" VerticalAlignment="Top" />
    <Button Content="Enviar" Height="23" HorizontalAlignment="Left" Margin="219,543,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    <TextBox Height="23" HorizontalAlignment="Left" Margin="228,135,0,0" Name="textBox1" VerticalAlignment="Top" Width="46" Text="00" />
    <Label Content=":" Height="28" HorizontalAlignment="Left" Margin="272,132,0,0" Name="label6" VerticalAlignment="Top" />
    <TextBox Height="23" HorizontalAlignment="Left" Margin="281,135,0,0" Name="textBox2" VerticalAlignment="Top" Width="46" Text="00" />
    <TextBox HorizontalAlignment="Left" Margin="228,168,0,0" Name="textBox3" Width="46" Height="23" VerticalAlignment="Top" Text="00" />
    <Label Content=":" Height="28" HorizontalAlignment="Left" Margin="272,166,0,0" Name="label7" VerticalAlignment="Top" />
    <TextBox Height="23" HorizontalAlignment="Left" Margin="281,168,0,0" Name="textBox4" VerticalAlignment="Top" Width="46" Text="00" />
    <TextBox Height="329" HorizontalAlignment="Left" Margin="78,208,0,0" Name="textBox5" VerticalAlignment="Top" Width="380" />
    <ListView Height="329" HorizontalAlignment="Left" Margin="709,208,0,0" Name="listView1" VerticalAlignment="Top" Width="480" SelectionChanged="listView1_SelectionChanged" SelectionMode="Single">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Entrou" Width="60" DisplayMemberBinding="{Binding hora_entrada}"/>
                <GridViewColumn Header="Saiu" Width="50" DisplayMemberBinding="{Binding hora_saida}" />
                <GridViewColumn Header="Conferido" Width="65" DisplayMemberBinding="{Binding visto}"/>
                <GridViewColumn Header="Descrição" Width="300" DisplayMemberBinding="{Binding descricao}"/>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using MySql.Data.MySqlClient;
    using System.Windows.Controls;
    using System.Collections.ObjectModel;
    namespace Clipboard_final
    {
public class Horarios
{
    public string hora_entrada{ get; set; }
    public string hora_saida { get; set; }
    public string visto { get; set; }
    public string descricao { get; set; }

}
public partial class Horas : UserControl
{
    private int id_user;
    ObservableCollection<Horarios> _Horarios =
    new ObservableCollection<Horarios>();
    public Horas(int _id_user)
    {
        id_user = _id_user;
        MySqlConnection oi = new MySqlConnection();
        oi.ConnectionString =
        "server=localhost;"
        + "database=clipboard;"
        + "uid=staff;"
        + "password=clipboardstaff4thewin;";
        try
        {
            oi.Open();
            MySqlCommand comando = new MySqlCommand("SELECT horario_entrada,horario_saida,visto,descricao from horarios where ID_Estagiario = @id_user", oi);
            comando.Parameters.Add("@id_user", MySqlDbType.Int32).Value = id_user;
            MySqlDataReader leitor = comando.ExecuteReader();
            while (leitor.Read())
            {
                Horarios horario = (new Horarios
                {
                    hora_entrada = leitor.GetString(0),
                    hora_saida = leitor.GetString(1),
                    visto = (leitor.GetChar(0)).ToString(),
                    descricao = leitor.GetString(2)
                });
                listView1.Items.Add(horario);
            }
            leitor.Close();
        }
        catch (MySqlException ex)
        {
            MessageBox.Show("Erro de conexão com o banco de dados. Erro " + ex.ToString());
        }
        InitializeComponent();
        label3.Content = "Hoje é dia "+Convert.ToString(DateTime.Now.Day)+" do mês "+Convert.ToString(DateTime.Now.Month)+" de "+Convert.ToString(DateTime.Now.Year);
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            MySqlConnection oi = new MySqlConnection();
            oi.ConnectionString =
            "server=localhost;"
            + "database=clipboard;"
            + "uid=staff;"
            + "password=clipboardstaff4thewin;";
            try
            {
                oi.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erro de conexão com o banco de dados. Erro " + ex.ToString());
            }
            if (textBox5.Text == "")
            {
                MessageBox.Show("Digite a descrição do dia");
            }
            else
            {
                MySqlCommand comando = new MySqlCommand("Select id_estagiario from estagiario where id_funcao = @um", oi);
                comando.Parameters.Add("@um", MySqlDbType.Int32).Value = 1;
                MySqlDataReader leitor = comando.ExecuteReader();
                int chefe = 0;
                while (leitor.Read())
                {
                    chefe = leitor.GetInt32(0);
                }
                leitor.Close();
                int horaentrada_inteiro = Convert.ToInt32(textBox1.Text);
                int minutosentrada_inteiro = Convert.ToInt32(textBox2.Text);
                int horasaida_inteiro = Convert.ToInt32(textBox3.Text);
                int minutossaida_inteiro = Convert.ToInt32(textBox4.Text);
                if (((horasaida_inteiro - horaentrada_inteiro) == 0 && (minutossaida_inteiro - minutosentrada_inteiro) <= 0) || horasaida_inteiro - horaentrada_inteiro < 0)
                {
                    MessageBox.Show("Você digitou incorretamente os horários");
                }
                if (horaentrada_inteiro < 13 || horasaida_inteiro > (DateTime.Now.Hour + 1))
                {
                    if (id_user != chefe)
                    {
                        MessageBox.Show("Ninguém trabalha nestes horários.", "Erro");
                        MySqlCommand comando1 = new MySqlCommand("Select Nome from estagiario where id_estagiario = @id_user", oi);
                        comando1.Parameters.Add("@id_user", MySqlDbType.Int32).Value = id_user;
                        MySqlDataReader leitor1 = comando1.ExecuteReader();
                        string nome = "";
                        while (leitor1.Read())
                        {
                            nome = leitor1.GetString(0);
                        }
                        leitor1.Close();
                        leitor1.Close();
                        comando1 = new MySqlCommand("Insert Into Recado values(0,@warn,0,'Clipboard SecuritySaver',@chefe)", oi);
                        comando1.Parameters.Add("@warn", MySqlDbType.VarChar).Value = "O estagiário " + nome + " tentou burlar o sistemas de horários.";
                        comando1.Parameters.Add("@chefe", MySqlDbType.Int32).Value = chefe;
                        comando1.ExecuteNonQuery();
                    }
                    else
                    {
                        MessageBox.Show("Chefe querido, você digitou os horários incorretamente", "Erro");
                    }
                }
                else
                {
                    string data = Convert.ToString(DateTime.Now.Day) + '/' + Convert.ToString(DateTime.Now.Month) + '/' + Convert.ToString(DateTime.Now.Year);
                    string hora_entrada = Convert.ToString(horaentrada_inteiro) + ':' + minutosentrada_inteiro.ToString();
                    string hora_saida = horasaida_inteiro.ToString() + ':' + minutossaida_inteiro.ToString();
                    comando = new MySqlCommand("INSERT INTO HORARIOS VALUES (0,@data,@id_user,@hora_entrada,@hora_saida,@descricao,0)", oi);
                    comando.Parameters.Add("@data", MySqlDbType.VarChar).Value = data;
                    comando.Parameters.Add("@id_user", MySqlDbType.Int32).Value = id_user;
                    comando.Parameters.Add("@hora_entrada", MySqlDbType.VarChar).Value = hora_entrada;
                    comando.Parameters.Add("@hora_saida", MySqlDbType.VarChar).Value = hora_saida;
                    comando.Parameters.Add("@descricao", MySqlDbType.VarChar).Value = textBox5.Text;
                    comando.ExecuteNonQuery();
                }
            }
        }

        catch (FormatException ex)
        {
            MessageBox.Show("Escreva somente números");
        }
    }
    private void listView1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
    }

    private void Grid_Loaded(object sender, RoutedEventArgs e)
    {

    }
}

}

抱歉使用了奇怪的语言

ListView对象引用未设置为对象的实例

尝试在表单初始化后调用listview项

表示listView1变量为null。在列表视图自身初始化之前,无法将项目添加到列表视图中。我假设listView1变量是在窗体的构造函数中自动初始化的,但用户控件的构造函数会提前被调用。

请注意,当您尝试在这些类的构造函数中初始化GUI控件时,这通常是一个糟糕的设计。我的意思是,GUI类的构造函数不应该使用其他GUI对象,因为在调用构造函数时,您永远无法确定它们是否已经初始化。