C# - ListBox控件

C# - ListBox控件 首页 / C#入门教程 / C# - ListBox控件

ListBox控件为无涯教程提供了一个显示项目列表的用户界面。从那里,用户可以从列表中选择一个或多个项目。可以使用列表框显示多个列,这些列可以包含图像和其他控件。

创建列表框控件

为了创建列表框,将在Windows窗体中遵循这两种方法。要创建ListBox控件,可以在设计时使用窗体设计器,也可以使用ListBox类在运行时创建控件。

在设计时创建列表框

在第一种方法中,将在设计时使用Windows窗体创建ListBox控件。

要创建ListBox控件,只需将ListBox控件从工具箱拖放到窗体即可。拖放列表框后,表单将如下图所示。当列表框显示在窗体上时,现在将使用鼠标调整其大小,并设置其属性和事件。

ListBox Control in C#

动态创建列表框的方法

ListBox类在Windows窗体中显示ListBox控件。为使运行时执行创建ListBox,首先,将创建ListBox类的实例并设置其属性,并将ListtBox对象添加到窗体控件。

步骤1.若要在第一步中创建动态列表框,将创建ListBox类的实例。

要创建列表框的对象,将编写以下代码:

ListBox List1 = new ListBox();

步骤2.在下一步中,将设置ListBox控件的属性。为此,将编写以下代码。在属性中设置列表框的位置、宽度、高度、背景色、前景色、名称、字体等属性,如下图所示:

ListBox box = new ListBox();
box.Location = new Point(300, 110);
box.Size = new Size(160, 103);
box.ForeColor = Color.Purple;
box.Items.Add(765);
box.Items.Add(875);
box.Items.Add(345);

步骤3.使用ListBox控件设置属性时,在下一步中,将向窗体添加列表框。为此,将使用Form.Controls.Add方法,该方法将把ListBox控件添加到窗体控件,并根据它们的位置和大小在窗体上显示它。

// Now we will add ListBox control 
            // to the form 
            this.Controls.Add(box);

现在,将编写一段代码,将该项添加到ListBox控件中并在列表中显示它们。

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

namespace WindowsFormsApp2
{
    public partial class Form1: Form
    {
        public Form1()
        {
            InitializeComponent();
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ListBox box = new ListBox();
            box.Location = new Point(300, 110);
            box.Size = new Size(160, 103);
            box.ForeColor = Color.Purple;
            box.Items.Add(765);
            box.Items.Add(875);
            box.Items.Add(345);

            // Now we will add ListBox control 
            // to the form 
            this.Controls.Add(box);
        }
        
    }
}

输出:

ListBox Control in C#

现在,将以另一个在运行时创建ListBox项的示例为例。

为此,AS将遵循与上述代码相同的步骤。

步骤1. 在第一步中,无涯教程将创建列表框的对象。为此,将编写以下代码:

ListBox ListItem = new ListBox();

步骤2.在下一步中,将设置ListBox控件的属性。将为位置、宽度、高度等编写代码。

ListItem.Location = new System.Drawing.Point(15, 15);
ListItem.Name = "ListItem";
ListItem.Size = new System.Drawing.Size(350, 400);
ListItem.BackColor = System.Drawing.Color.Orange;
ListItem.ForeColor = System.Drawing.Color.Black;

步骤3.现在,将使用以下代码在运行时将该项添加到列表框中。

ListItem.Items.Add("Vaishali Tyagi");
ListItem.Items.Add("Samlesh Tyagi");
ListItem.Items.Add("Preeti Tyagi");
ListItem.Items.Add("Priyanka Tyagi");

步骤4.在下一步中,将向窗体添加列表框。为此,将使用Forms.Controls.Add方法

,该方法帮助无涯教程将列表框控件添加到窗体控件,并根据控件的位置和大小将其显示在窗体上。

this.Controls.Add(ListItem);

现在,无涯教程将用C#编写代码来创建Windows窗体中的ListBox控件。

示例2。

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp2 { public partial class Form1: Form { public Form1() { InitializeComponent(); } ListBox ListItem = new ListBox(); private void Form1_Load(object sender, EventArgs e) { ListItem.Location = new System.Drawing.Point(15, 15); ListItem.Name = "ListItem"; ListItem.Size = new System.Drawing.Size(350, 400); ListItem.BackColor = System.Drawing.Color.Orange; ListItem.ForeColor = System.Drawing.Color.Black; ListItem.Items.Add("Vaishali Tyagi"); ListItem.Items.Add("Samlesh Tyagi"); ListItem.Items.Add("Preeti Tyagi"); ListItem.Items.Add("Priyanka Tyagi"); this.Controls.Add(ListItem); } } }

输出:

ListBox Control in C#

列表框名称属性

Name属性表示列表框控件的唯一名称。在代码中使用此名称来访问控件。下面的代码设置并获取ListBox控件的文本的名称。

ListItem.Name = "ListItem";

列表框的位置、高度、宽度和大小属性

Location  -   Location属性包含一个点,该点显示窗体上列表框的起始位置。还可以使用Left和Top属性从窗体的左上角显示控件的位置。

Size            -  Size属性显示控件的大小。还可以使用Width和Height属性代替Size属性。为此将编写以下代码来设置ListBox控件的位置、高和宽度属性。

ListItem.Location = new System.Drawing.Point(15, 15);
ListItem.Size = new System.Drawing.Size(350, 400); 

列表框的字体

Font属性显示ListBox控件的文本的字体。当单击"Properties"窗口中的字体属性时,可以看到字体的名称、大小和字体的其他选项。为此将编写以下代码,该代码在运行时设置Font属性。

ListItem.Font = new Font("Georgia", 16);

列表框的背景色和前景色

要设置列表框的背景色和前景色,使用了BackColor和Forecolor属性。在属性窗口中单击这些属性后,将出现一个彩色对话框。

为此,将编写以下代码:

ListItem.BackColor = System.Drawing.Color.Orange;
ListItem.ForeColor = System.Drawing.Color.Black;

创建应用程序

对于应用程序的创建,将设计一个用户界面,其中的界面包含两个列表框(listbox1和listbox2)、包含不同功能的五个按钮,即将第一个列表框中的数据添加到第二个列表框、删除数据、全部添加、全部删除、完成以及将在其中显示最终数据的GridView。

要设计图形用户界面,将执行以下步骤:

第1步.在第一步中,将创建一个用于创建项目的新项目;将按照以下步骤进行操作:

单击New->Project...,如下面的屏幕截图所示。

ListBox Control in C#

第2步。之后,将显示一个新窗口,程在其中选择项目的Visual C#->Windows窗体应用程序->名称(AddRemoveCreation),然后单击确定,如下面的屏幕截图所示。

ListBox Control in C#

第3步。之后,将创建如下截图所示的表单:

ListBox Control in C#

第4步.在下一步中,将从工具箱中拖放列表框。这里将使用两个列表框(ListBox1和ListBox2)和五个按钮(Add、Remove、Add All、Remove All和Finalize)。

ListBox Control in C#

第5步.在下一步中,无涯教程将通过右键单击按钮来更改按钮的文本和名称->选择属性->更改文本名称,如以下截图所示:

ListBox Control in C#

第6步。单击属性后,将打开属性窗口,将在其中更改按钮的名称和按钮上的文本,如以下屏幕截图所示:

ListBox Control in C#

第7步。之后,将在单击GridView中的Finalize按钮后显示数据。为此,将单击Data->GridView

ListBox Control in C#

之后,页面如下图所示:

ListBox Control in C#

Listbox1添加数据,并在ListBox2中导入数据。

为此,无涯教程将执行以下代码:

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

namespace AddRemoveCreation
{
     public partial class Form1: Form
    {
        //create an object dtCourse of the DataTable.
        private DataTable dtCourse = new DataTable();
        //create an object dtSelectedCourse of the DataTable.
        private DataTable dtSelectedCourse = new DataTable();

        public Form1()
        {
            //InitializeComponent() is used to initialize the form.
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //call the function at the form loading
            FillCouseTable();
            SelectedCourseTable();
            //Add the value in the DataSource of the ListBox1
            listBox1.DataSource = dtCourse;
            //listbox1.DisplayMember is used to decide which column we want to show in the final output
            listBox1.DisplayMember = "CourseName";
            //dtSelectedCourse datatable add the value in the listbox2 datasource
            listBox2.DataSource = dtSelectedCourse;
            listBox2.DisplayMember = "CourseName";


        }
        //FillCourseTable() function is declare to add the data in the datatable with the help of the data object
        private void FillCouseTable()
        {
            //adding the column name
            dtCourse.Columns.Add("CourseID", typeof(int));
            dtCourse.Columns.Add("CourseName");
            dtCourse.Columns.Add("CourseDuration");
            //add the data in the dtCourse table 
            dtCourse.Rows.Add(1, "Advance OOPS", "4 Months");
            dtCourse.Rows.Add(2, "Data Structure", "5 Months");
            dtCourse.Rows.Add(3, "Java", "6 Months");
            dtCourse.Rows.Add(4, "C++", "3 Months");
            dtCourse.Rows.Add(5, "C", "2 Months");


        }
        //SelectedCourseTable() function is declare which contain the column name of the data table.
        private void SelectedCourseTable()
        {
            dtSelectedCourse.Columns.Add("CourseID", typeof(int));
            dtSelectedCourse.Columns.Add("CourseName");
            dtSelectedCourse.Columns.Add("CourseDuration");

        }
        //After clicking on the add button function Addbtn_Click() is create which contain the functionality of Add button

        private void Addbtn_Click(object sender, EventArgs e)
        {
            //if the condition applies if the listbox1 contain the item greater than zero then this will import the data in the listbox2 and delete the data from the listbox1
            if(listBox1.Items.Count>0)
            {
                //Here we are improting the data to the dtSelectedCourse datatable from the dtcourse datatable
                dtSelectedCourse.ImportRow(dtCourse.Rows[listBox1.SelectedIndex]);
                dtCourse.Rows[listBox1.SelectedIndex].Delete();
            }
        }

这里将显示包含数据的listbox1。

ListBox Control in C#

单击Add按钮后,数据将添加到listbox2,并从listbox1中删除。

ListBox Control in C#

从列表框中删除数据

这里将展示如何从listbox2中删除数据。

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

namespace AddRemoveCreation
{
     public partial class Form1: Form
    {
        //create an object dtCourse of the DataTable.
        private DataTable dtCourse = new DataTable();
        //create an object dtSelectedCourse of the DataTable.
        private DataTable dtSelectedCourse = new DataTable();

        public Form1()
        {
            //InitializeComponent() is used to initialize the form.
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //call the function at the form loading
            FillCouseTable();
            SelectedCourseTable();
            //Add the value in the DataSource of the ListBox1
            listBox1.DataSource = dtCourse;
            //listbox1.DisplayMember is used to decide which column we want to show in the final output
            listBox1.DisplayMember = "CourseName";
            //dtSelectedCourse datatable add the value in the listbox2 datasource
            listBox2.DataSource = dtSelectedCourse;
            listBox2.DisplayMember = "CourseName";


        }
        //FillCourseTable() function is declare to add the data in the datatable with the help of the data object
        private void FillCouseTable()
        {
            //adding the column name
            dtCourse.Columns.Add("CourseID", typeof(int));
            dtCourse.Columns.Add("CourseName");
            dtCourse.Columns.Add("CourseDuration");
            //add the data in the dtCourse table 
            dtCourse.Rows.Add(1, "Advance OOPS", "4 Months");
            dtCourse.Rows.Add(2, "Data Structure", "5 Months");
            dtCourse.Rows.Add(3, "Java", "6 Months");
            dtCourse.Rows.Add(4, "C++", "3 Months");
            dtCourse.Rows.Add(5, "C", "2 Months");


        }
        //SelectedCourseTable() function is declare which contain the column name of the data table.
        private void SelectedCourseTable()
        {
            dtSelectedCourse.Columns.Add("CourseID", typeof(int));
            dtSelectedCourse.Columns.Add("CourseName");
            dtSelectedCourse.Columns.Add("CourseDuration");

        }
        

//After clicking on the Remove button Removebtn_Click() function is created where we remove the element from the listbox2 and import the data in the data table.

        private void Removebtn_Click(object sender, EventArgs e)
        {
            //for removing the element we apply condition if listbox contain the element greater than zero
            if (listBox2.Items.Count > 0)
            {
                //here the data will be import to the datatable dtcourse from the dtSelected Database.
                dtCourse.ImportRow(dtSelectedCourse.Rows[listBox2.SelectedIndex]);
                //All data will be deleted from the datatable dtSelectedCourse
                dtSelectedCourse.Rows[listBox2.SelectedIndex].Delete();
            }
        }
}
}

在删除数据之前,整个数据都在listbox2中,而listbox1不包含任何值。输出将如下所示:

ListBox Control in C#

单击Remove按钮后,数据将从列表框2中删除,并添加到列表框1中,如下面的屏幕截图所示:

ListBox Control in C#

在列表框中一次性添加全部数据

为了将listbox1中的完整数据添加到listbox2中,将编写如下代码:

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

namespace AddRemoveCreation
{
     public partial class Form1: Form
    {
        //create an object dtCourse of the DataTable.
        private DataTable dtCourse = new DataTable();
        //create an object dtSelectedCourse of the DataTable.
        private DataTable dtSelectedCourse = new DataTable();

        public Form1()
        {
            //InitializeComponent() is used to initialize the form.
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //call the function at the form loading
            FillCouseTable();
            SelectedCourseTable();
            //Add the value in the DataSource of the ListBox1
            listBox1.DataSource = dtCourse;
            //listbox1.DisplayMember is used to decide which column we want to show in the final output
            listBox1.DisplayMember = "CourseName";
            //dtSelectedCourse datatable add the value in the listbox2 datasource
            listBox2.DataSource = dtSelectedCourse;
            listBox2.DisplayMember = "CourseName";


        }
        //FillCourseTable() function is declare to add the data in the datatable with the help of the data object
        private void FillCouseTable()
        {
            //adding the column name
            dtCourse.Columns.Add("CourseID", typeof(int));
            dtCourse.Columns.Add("CourseName");
            dtCourse.Columns.Add("CourseDuration");
            //add the data in the dtCourse table 
            dtCourse.Rows.Add(1, "Advance OOPS", "4 Months");
            dtCourse.Rows.Add(2, "Data Structure", "5 Months");
            dtCourse.Rows.Add(3, "Java", "6 Months");
            dtCourse.Rows.Add(4, "C++", "3 Months");
            dtCourse.Rows.Add(5, "C", "2 Months");


        }
        //SelectedCourseTable() function is declare which contain the column name of the data table.
        private void SelectedCourseTable()
        {
            dtSelectedCourse.Columns.Add("CourseID", typeof(int));
            dtSelectedCourse.Columns.Add("CourseName");
            dtSelectedCourse.Columns.Add("CourseDuration");

        }
        //After clicking on the AddAll button AddAllbtn_Click() function is create. 
        private void AddAllbtn_Click(object sender, EventArgs e)
        {
            //if condition is apply this will check if the listbox contain the element greater than zero.
            if(listBox1.Items.Count>0)
            {
                //dtCourse.Rows.Count will count the element and assign the value in the count variable.
                int count = dtCourse.Rows.Count;
                //for condition is apply this will going upto the count
                for(int i=count-1;i>=0;i--)
                {
                    //dtCourse.Rows[listbox1.SelectedIndex] with the help of this data will be import to the dtSelected datatable.
                    dtSelectedCourse.ImportRow(dtCourse.Rows[listBox1.SelectedIndex]);
                    //with this code data eill be delete from the dtCourse datatable.
                    dtCourse.Rows[listBox1.SelectedIndex].Delete();

                }
            }
        }
}
}

listbox1中的数据如下所示:

ListBox Control in C#

编写此代码后,AddAll按钮将起作用,如下图所示:

ListBox Control in C#

从列表框中删除所有数据

这里,将从listbox2中删除所有数据,并添加listbox1中的所有数据。

要从列表框中删除所有数据,将编写以下代码,如下所示:

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

namespace AddRemoveCreation
{
     public partial class Form1: Form
    {
        //create an object dtCourse of the DataTable.
        private DataTable dtCourse = new DataTable();
        //create an object dtSelectedCourse of the DataTable.
        private DataTable dtSelectedCourse = new DataTable();

        public Form1()
        {
            //InitializeComponent() is used to initialize the form.
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //call the function at the form loading
            FillCouseTable();
            SelectedCourseTable();
            //Add the value in the DataSource of the ListBox1
            listBox1.DataSource = dtCourse;
            //listbox1.DisplayMember is used to decide which column we want to show in the final output
            listBox1.DisplayMember = "CourseName";
            //dtSelectedCourse datatable add the value in the listbox2 datasource
            listBox2.DataSource = dtSelectedCourse;
            listBox2.DisplayMember = "CourseName";


        }
        //FillCourseTable() function is declare to add the data in the datatable with the help of the data object
        private void FillCouseTable()
        {
            //adding the column name
            dtCourse.Columns.Add("CourseID", typeof(int));
            dtCourse.Columns.Add("CourseName");
            dtCourse.Columns.Add("CourseDuration");
            //add the data in the dtCourse table 
            dtCourse.Rows.Add(1, "Advance OOPS", "4 Months");
            dtCourse.Rows.Add(2, "Data Structure", "5 Months");
            dtCourse.Rows.Add(3, "Java", "6 Months");
            dtCourse.Rows.Add(4, "C++", "3 Months");
            dtCourse.Rows.Add(5, "C", "2 Months");


        }
        //SelectedCourseTable() function is declare which contain the column name of the data table.
        private void SelectedCourseTable()
        {
            dtSelectedCourse.Columns.Add("CourseID", typeof(int));
            dtSelectedCourse.Columns.Add("CourseName");
            dtSelectedCourse.Columns.Add("CourseDuration");

        }

//After clicking on the Remove button RemoveAllbtn_Click() function is create. 

        private void RemoveAllbtn_Click(object sender, EventArgs e)
        {
            //if the condition is applied, this will count the listbox2 containing the value.

            if (listBox2.Items.Count > 0)
            {
                int count = dtSelectedCourse.Rows.Count;
                //for loop is apply which will go upto the greater than zero 
                for (int i = count - 1; i >= 0; i--)
                {
                    //dtCourse datatable import the data from the dtSelectedCourse datatable.
                    dtCourse.ImportRow(dtSelectedCourse.Rows[listBox2.SelectedIndex]);
                    //data will be deleted from the dtSelectedCourse datatable.
                    dtSelectedCourse.Rows[listBox2.SelectedIndex].Delete();
                }
                    
            }
        }
}
}
ListBox Control in C#

在GridView中显示列表框的数据

在这里,将在单击Finalize按钮后使用GridView显示ListBox2的所有数据。要在GridView中显示数据,将编写以下代码:

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

namespace AddRemoveCreation
{
    public partial class Form1: Form
    {
        //create an object dtCourse of the DataTable.
        private DataTable dtCourse = new DataTable();
        //create an object dtSelectedCourse of the DataTable.
        private DataTable dtSelectedCourse = new DataTable();

        public Form1()
        {
            //InitializeComponent() is used to initialize the form.
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //call the function at the form loading
            FillCouseTable();
            SelectedCourseTable();
            //Add the value in the DataSource of the ListBox1
            listBox1.DataSource = dtCourse;
            //listbox1.DisplayMember is used to decide which column we want to show in the final output
            listBox1.DisplayMember = "CourseName";
            //dtSelectedCourse datatable add the value in the listbox2 datasource
            listBox2.DataSource = dtSelectedCourse;
            listBox2.DisplayMember = "CourseName";


        }
        //FillCourseTable() function is declare to add the data in the datatable with the help of the data object
        private void FillCouseTable()
        {
            //adding the column name
            dtCourse.Columns.Add("CourseID", typeof(int));
            dtCourse.Columns.Add("CourseName");
            dtCourse.Columns.Add("CourseDuration");
            //add the data in the dtCourse table 
            dtCourse.Rows.Add(1, "Advance OOPS", "4 Months");
            dtCourse.Rows.Add(2, "Data Structure", "5 Months");
            dtCourse.Rows.Add(3, "Java", "6 Months");
            dtCourse.Rows.Add(4, "C++", "3 Months");
            dtCourse.Rows.Add(5, "C", "2 Months");


        }
        //SelectedCourseTable() function is declare which contain the column name of the data table.
        private void SelectedCourseTable()
        {
            dtSelectedCourse.Columns.Add("CourseID", typeof(int));
            dtSelectedCourse.Columns.Add("CourseName");
            dtSelectedCourse.Columns.Add("CourseDuration");

        }

//Clicking on the Finalize button Finalizebtn_Click() function is create 

        private void Finalizebtn_Click(object sender, EventArgs e)
        {
            // create an object of the DialoResult where we will show the message with the help of the MessageBox.Show() function.
            DialogResult dialog=MessageBox.Show("Are you sure you want to finalize the selected course", "Confirmation Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            //Condition is apply if the result is yes.
            if(dialog==DialogResult.Yes)
            {
                //Shows the result of the dtSelectedCourse datatable to GridView.
                dataGridView1.DataSource = dtSelectedCourse;
                //to stop the editing we enable the datagridview to false.
                dataGridView1.Enabled = false;
                //With this code we apply the visiblity of the column index 0 to false.
                dataGridView1.Columns[0].Visible = false;
                //hide the header value of the row
                dataGridView1.RowHeadersVisible = false;
            }
            else
            {
                //If the result no, then shows the message with the help of the MessageBox.Show(). 
                MessageBox.Show("Please Select Atleast one course","Information Message", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            }
        }
}
}

单击Finalize按钮后,将显示确认消息。

ListBox Control in C#

单击YES后,聚合数据将显示在GridView中,如下面的屏幕截图所示:

ListBox Control in C#

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

人工智能基础课 -〔王天一〕

深入剖析Kubernetes -〔张磊〕

从0开发一款iOS App -〔朱德权〕

说透敏捷 -〔宋宁〕

React Hooks 核心原理与实战 -〔王沛〕

说透区块链 -〔自游〕

深入剖析Java新特性 -〔范学雷〕

徐昊 · TDD项目实战70讲 -〔徐昊〕

B端产品经理入门课 -〔董小圣〕

好记忆不如烂笔头。留下您的足迹吧 :)