从表中获取结果,将它们存储在数组中然后显示它们

时间:2014-09-20 08:37:32

标签: c# mysql

我一直试图解决这个问题已经有一段时间了,但是我可以解决这里的确切问题。 我有一个具有ID,first_name和surname的表。我试图从这个表中拉出一行,将其存储在一个数组中,然后将其显示在一个列表框中。这就是我所拥有的

        public Contacts[] getAllContacts()
    {
        List<Contacts> theContactList = new List<Contacts>();

        try
        {

            conn = new MySqlConnection(cs);
            conn.Open();

            string stm = "select id, first_name, surname from contacts";
            MySqlCommand cmd = new MySqlCommand(stm, conn);
            rdr = cmd.ExecuteReader();

            while (rdr.Read())
            {
                Contacts theContact = new Contacts();
                theContact.contactID = rdr.GetInt32("id");
                theContact.first_name = rdr.GetString("first_name");
                theContact.surname = rdr.GetString("surname");

                theContactList.Add(theContact);

            }
        }
        catch (MySqlException ex)
        {
            System.Diagnostics.Debug.WriteLine("Error: {0}", ex.ToString());
        }
        finally
        {
            if (rdr != null)
            {
                rdr.Close();
            }

            if (conn != null)
            {
                conn.Close();
            }

        }
        if (theContactList.Count > 0)
        {
            return theContactList.ToArray();
        }
        else
        {
            return null;
        }
    }

这是我用来拉取值的方法,现在在另一个类我用它来显示列表框中的值。

        ContactManager contactMan = new ContactManager();
    public Form1()
    {
        InitializeComponent();
        reloadContacts();
    }




    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (listBox1.SelectedIndex > 0)
        {
            Contacts currentContact = (Contacts)listBox1.SelectedItem;

            textBox1.Text = currentContact.contactID.ToString();
            textBox2.Text = currentContact.surname;
            textBox3.Text = currentContact.first_name;


        }
    }

    private void reloadContacts()
    {
        listBox1.Items.Clear();
        Contacts[] allContacts = contactMan.getAllContacts();


        foreach (Contacts b in allContacts)
        {
            listBox1.Items.Add(b);

        }

}

现在让我感到困惑的是显示的内容。我一直在改变我的表格,我发现在列表框中它会为每一行显示“ProjectName.Contacts”,但列表框中的第一个条目在选中时不会显示任何信息,而别人这样做。

有关如何解决此问题的任何帮助?

谢谢!

2 个答案:

答案 0 :(得分:1)

ListBox将使用该对象的ToString()方法显示您放入其中的任何对象。如果不重写此方法,它将返回自定义类的类名。这就是发生的事。

您需要决定要显示的内容。首先使用listBox1.Items.Add(b.surname);查看您的数据是否存在。使用格式字符串可以产生更好的结果,或者使用ListView为数据创建列。

答案 1 :(得分:1)

我认为你的问题在这里:

if (listBox1.SelectedIndex > 0)
{
    Contacts currentContact = (Contacts)listBox1.SelectedItem;

     textBox1.Text = currentContact.contactID.ToString();
     textBox2.Text = currentContact.surname;
     textBox3.Text = currentContact.first_name;
}

未选择SelectedIndex = -1。 0是第一个元素。尝试:

if (listBox1.SelectedIndex != -1)
{
相关问题