如何在C#中获取双列Winform列表框?

4

我正在使用MySQL和C#开发一个学生考勤项目。在这个项目中,我想把一个列表框中的数据移动到另一个列表框中。我已经完成了这个功能。但是我需要在其中加载学生姓名。现在客户要求姓名和管理员编号像datagridview列一样显示。

我搜索了一下,VB有这种类型的编码。请参见多列列表框。在C#中是否可能实现?

enter image description here

请看下面的图片。这是我的表格。

enter image description here

我的代码用于加载列表框

        MySqlConnection connection = new MySqlConnection(MyConString);
        MySqlCommand command = connection.CreateCommand();
        MySqlDataReader Reader;
        command.CommandText = "select name,admin_no from student_admision_master where course='" + course_code + "' AND year='" + year_code + "' AND sem='" + semester_code + "' AND batch='" + batch_code + "'";
        connection.Open();
        Reader = command.ExecuteReader();
        while (Reader.Read())
        {
            listBox1.Items.Add(Reader[0].ToString() + "," + Reader[1].ToString());
        }
        connection.Close();

这会给出结果 jagadees,125445。但是想要分离不同的列。 移动数据的代码:
private void btn_toAb_Click_Click(object sender, EventArgs e)
{
    int count = listBox1.Items.Count;
    for (int i = 0; i < count; i++)
    {
        listBox2.Items.Add(listBox1.Items[i].ToString());
    }
    listBox1.Items.Clear();
}

private void btn_fromAb_Click_Click(object sender, EventArgs e)
{
    int count = listBox2.Items.Count;
    for (int i = 0; i < count; i++)
    {
        listBox1.Items.Add(listBox2.Items[i].ToString());
    }
    listBox2.Items.Clear();
}

private void btn_toAb_Selected_Click(object sender, EventArgs e)
{
    int count = listBox1.SelectedItems.Count;
    for (int i = 0; i < count; i++)
    {
        listBox2.Items.Add(listBox1.SelectedItems[i].ToString());
    }

    for (int i = 0; i < count; i++)
    {
        listBox1.Items.Remove(listBox1.SelectedItems[0]);
        //listBox1.add

    }
}

private void btn_fromAb_Selected_Click(object sender, EventArgs e)
{
    int count = listBox2.SelectedItems.Count;
    for (int i = 0; i < count; i++)
    {
        listBox1.Items.Add(listBox2.SelectedItems[i].ToString());
    }

    for (int i = 0; i < count; i++)
    {
        listBox2.Items.Remove(listBox2.SelectedItems[0]);
    }
}

Thanks in advance!...

2个回答

10

Windows Forms控件"ListView"可以实现这一功能。


2

您可以使用String.Format()方法来实现这一功能。在每个方法内部,您可以定义每行中每个项目的对齐方式。 我没有数据库,但是在我的示例中,我使用了两个数组(与您的reader [0]和reader [1]索引器相同)。因此,您可以使用Reader [0]和Reader [1]而不是array1 [i]和array2 [i]。 以下是示例:

        string[] array1 = { "name 1", "name10", "name104", "name 222", "name 3212" };
        string[] array2 = { "12343", "23", "432", "4333", "1" };

        const int a = 40;
        int b = 0;

        for (int i = 0; i < array1.Length; i++)
        {
            if (array1[i].Contains(' '))
                b = array1[i].Length - 1;
            else
                b = array1[i].Length;
            b = -(a - b);
            listBox1.Items.Add(String.Format("{0," + b + "} {1}", array1[i], array2[i]));
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接