2024年5月6日发(作者:)
ListBox控件
1.功能
ListBox控件显示较长的选项列表,用户可从中选择一项或多项。如果项总数超出可以显示
的项数,则自动向ListBox控件添加滚动条。ListBox控件列表中的每个元素称为项。图1
所示为ListBox控件。
图1 ListBox控件
2.属性
ListBox控件常用属性及说明如表1所示。
表1 ListBox控件常用属性及说明
下面对比较重要的属性进行详细介绍。
(1)Items属性。该属性用于查看列表框中的项。
语法:
public ObjectCollection Items { get; }
属性值:Collection表示ListBox中的项。
说明:
① 该属性使用户可以获取对当前存储在 ListBox 中的项列表的引用。通过此引用,可以在
集合中添加项、移除项和获得项的计数。
② 可以使用DataSource属性来操控ListBox的项。如果使用DataSource属性向ListBox
添加项,则可以使用Items属性查看ListBox中的项,但不能使用
Collection的方法向该列表添加项或从中移除项。
(2)SelectedItem属性。该属性表示当前选中的项。
语法:
public Object SelectedItem { get; set; }
属性值:表示控件中当前选定内容的对象。
说明:对于标准 ListBox,可以使用此属性确定在ListBox中选定了哪个项。如果 ListBox
的SelectionMode属性设置为imple或
xtended(它指示多重选择ListBox),并在该列表中选定了多个项,
则此属性可返回任何选定的项。
示例
把左边的文本框中的内容移到右边的文本框中
本示例主要使用Items属性向ListBox1控件添加项,然后使用SelectedItem属性将
ListBox1控件中的选中项添加到ListBox2控件中。示例运行结果如图2和图3所示。
图2 ListBox1中项移动前
图3 ListBox1中项移动后
程序主要代码如下:
SqlConnection con = new SqlConnection("server=ZHYzhy;uid=sa;pwd=;database=student");
();
SqlCommand com = new SqlCommand("select * from student",con);
SqlDataReader dr = eReader();
();
while (())
{
// (dr[0].ToString());
(dr[1].ToString());
// (dr[2].ToString());
}
();
();
注意:此示例使用了数据库,所以需要引用命名空间using ent。
完整程序代码如下:
★★★★★主程序文件完整程序代码★★★★★
using System;
using c;
using ;
namespace _8_05
{
static class Program
{
///
/// 应用程序的主入口点。
///
[STAThread]
static void Main()
{
VisualStyles();
patibleTextRenderingDefault(false);
(new frmListBox());
}
}
}
C#中改变listbox的item颜色的方法
(1)需要先设置属性:
该事件由所有者描述的 ListBox 使用。仅当 DrawMode 属性设置为
rawFixed 或 rawVariable 时,才引发该事件。可以使
用该事件来执行在 ListBox 中绘制项所需的任务。如果具有大小可变的项(当 DrawMode
属性设置为 rawVariable 时),在绘制项前,引发 MeasureItem 事件。
可以为 MeasureItem 事件创建事件处理程序,以在 DrawItem 事件的事件处理程序中指定
要绘制的项的大小。有关处理事件的更多信息,请参见 使用事件。
(2)重写listbox的drawitem事件
private void listBox1_DrawItem(object sender, emEventArgs
e){ // Set the DrawMode property to draw fixed sized items.
de = rawFixed;
// Draw the background of the ListBox control for each item.
ckground(); // Define the default color of the brush as black.
Brush myBrush = ;
// Determine the color of the brush to draw each item based on the index of the item to draw.
switch () { case 0: myBrush = ; break;
case 1: myBrush = ; break;
case 2: myBrush = ; break; }
// Draw the current item text based on the current Font and the custom brush settings.
ring([].ToString(), , myBrush,
,cDefault);
// If the ListBox has focus, draw a focus rectangle around the selected item.
cusRectangle();}
(3)从这个例子,我们发现在c#下面重画控件,比在vc++6.0中定义自绘方便多了
发布评论