All articles(网络文学目录) All Pictures(图片目录) All Softwares(软件目录)

 
C#中ListBox控件应用实例

Writer: qq Article type: Programming skills(编程技巧) Time: 2014/7/11 9:17:16 Browse times: 394 Comment times: 0

C#中ListBox控件应用实例


Head photo

Go homepage
Upload pictures
Write articles

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窗体设计文件完整程序代码★★★★★




There are 0 records,
Comment:
Must be registered users to comment(必须是注册用户才能发表评论)

Disclaimer Privacy Policy About us Site Map
Copyright ©2011-
uuhomepage.com, Inc. All rights reserved.