1. 引用System.Configuration命名空间

2. 使用App.config中的连接字符串
- App.config配置:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="DataFormConnection"
connectionString="Data Source=abcdd;database=xyz;uid=4566;pwd=987"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
- C#代码引用
public void BindComboBox(ComboBox comboBoxName)
{
SqlConnection conn = new SqlConnection("your connection string");
SqlDataAdapter da = new SqlDataAdapter("Select ZoneId,ZoneName FROM tblZones", conn);
DataSet ds = new DataSet();
da.Fill(ds, "tblZones");//此处可以直接使用da.Fill(ds);
comboBoxName.ItemsSource = ds.Tables[0].DefaultView;
comboBoxName.DisplayMemberPath = ds.Tables[0].Columns["ZoneName"].ToString();
comboBoxName.SelectedValuePath = ds.Tables[0].Columns["ZoneId"].ToString();
}
private void btnZone_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Selected ZoneName="+ComboBoxZone.Text+" and ZoneId="+ ComboBoxZone.SelectedValue.ToString());
}
3. 扩展阅读
Connection Strings and Configuration Files
本文介绍如何在C#中使用App.config文件中的连接字符串来绑定ComboBox控件。通过具体的代码示例展示了如何从数据库中获取数据并填充ComboBox,包括设置显示成员和选择值。
7348

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



