ComboBox的Item

本文详细介绍了如何通过数据库填充ComboBox的实现步骤,并解释了使用BeginUpdate()和EndUpdate()方法防止闪烁的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1. 如果是静态地在下拉表单中显示Item, 可以通过设置ComboBox的Items属性编辑.
2. 还可以动态地显示Item, 即从数据库中读取要显示的Items.
书上看到的方法:使用DataSet填充
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

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

        
private void Form1_Load(object sender, EventArgs e)
        {
            
this.comboBox1.Items.Clear();
            
string connString = @"Server=localhost;Integrated Security=True; Database=Test";
            SqlConnection thisConnection 
= new SqlConnection(connString);
            
string strSql = "select distinct UserName from TestTable";
            SqlDataAdapter thisAdapter 
= new SqlDataAdapter(strSql,thisConnection);
            DataSet thisDateSet 
= new DataSet();
            thisAdapter.Fill(thisDateSet);

            
this.comboBox1.BeginUpdate();
            
this.comboBox1.DataSource = thisDateSet.Tables[0];
            
this.comboBox1.DisplayMember = "UserName";
            
this.comboBox1.ValueMember = "UserName";
            
this.comboBox1.EndUpdate();
        }
    }
}
使用BeginUpdate()方法可以防止每次向Items添加项时都重新绘制 ComboBox, 完成向列表添加项的任务后, 调用EndUpdate()方法来使ComboBox能够重新绘制. 当向列表添加大量的项时, 使用这种方法可以防止绘制ComboBox时闪烁.
??这里没有打开数据库连接, 为什么能得到数据库中的值? DataAdapter不需要打开连接?
MSDN上给出的DataAdapter示例:
Code
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值