1. 如果是静态地在下拉表单中显示Item, 可以通过设置ComboBox的Items属性编辑.
2. 还可以动态地显示Item, 即从数据库中读取要显示的Items.
书上看到的方法:使用DataSet填充
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
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示例:
本文详细介绍了如何通过数据库填充ComboBox的实现步骤,并解释了使用BeginUpdate()和EndUpdate()方法防止闪烁的效果。
1701

被折叠的 条评论
为什么被折叠?



