Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)qq
published in(发表于) 2014/7/11 9:17:16
C#中ListBox控件应用实例

C#中ListBox控件应用实例

ListBox控件

1.功能

ListBox控件显示较长的选项列表,用户可从中选择一项或多项。如果项总数超出可以显示的项数,则自动向ListBox控件添加滚动条。ListBox控件列表中的每个元素称为项。图1所示为ListBox控件。



图1 ListBox控件

2.属性

ListBox控件常用属性及说明如表1所示。



表1 ListBox控件常用属性及说明

下面对比较重要的属性进行详细介绍。

(1)Items属性。该属性用于查看列表框中的项。

语法:

public ObjectCollection Items { get; }
属性值:ListBox.ObjectCollection表示ListBox中的项。

说明:

① 该属性使用户可以获取对当前存储在 ListBox 中的项列表的引用。通过此引用,可以在集合中添加项、移除项和获得项的计数。

② 可以使用DataSource属性来操控ListBox的项。如果使用DataSource属性向ListBox添加项,则可以使用Items属性查看ListBox中的项,但不能使用ListBox.ObjectCollection的方法向该列表添加项或从中移除项。

(2)SelectedItem属性。该属性表示当前选中的项。

语法:

public Object SelectedItem { get; set; }
属性值:表示控件中当前选定内容的对象。

说明:对于标准 ListBox,可以使用此属性确定在ListBox中选定了哪个项。如果 ListBox的SelectionMode属性设置为SelectionMode.MultiSimple或SelectionMode.MultiExtended(它指示多重选择ListBox),并在该列表中选定了多个项,则此属性可返回任何选定的项。

示例

把左边的文本框中的内容移到右边的文本框中

本示例主要使用Items属性向ListBox1控件添加项,然后使用SelectedItem属性将ListBox1控件中的选中项添加到ListBox2控件中。示例运行结果如图2和图3所示。



图2 ListBox1中项移动前



图3 ListBox1中项移动后

程序主要代码如下:

SqlConnection con = new SqlConnection("server=ZHYzhy;uid=sa;pwd=;database=student");

con.Open();

SqlCommand com = new SqlCommand("select * from student",con);

SqlDataReader dr = com.ExecuteReader();

this.listBox1.Items.Clear();

while (dr.Read())

{

// this.listBox1.Items.Add(dr[0].ToString());

this.listBox1.Items.Add(dr[1].ToString());

// this.listBox1.Items.Add(dr[2].ToString());

}

dr.Close();

con.Close();

注意:此示例使用了数据库,所以需要引用命名空间using System.Data.SqlClient。

完整程序代码如下:

★★★★★主程序文件完整程序代码★★★★★

using System;

using System.Collections.Generic;

using System.Windows.Forms;

namespace _8_05

{

static class Program

{

///



/// 应用程序的主入口点。

///


[STAThread]

static void Main()

{

Application.EnableVisualStyles();

Application.SetCompatibleTextRenderingDefault(false);

Application.Run(new frmListBox());

}

}

}

★★★★★Form1窗体设计文件完整程序代码★★★★★


If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759