【问题标题】:Bind few columns to combobox将几列绑定到组合框
【发布时间】:2011-06-28 17:10:19
【问题描述】:

我在数据集中有两个表

城市和国家。

我想在组合框中显示城市名称和国家名称。

我的表格显示为:

Cities:
int ID 
varchar(max) Name
varchar(2) CountryCode

Countries:
varchar(2) Code
varchar(max) Name

现在,我的组合框显示为:

 dictionaryData1.Cities.DefaultView.Sort = dictionaryData1.Cities.NameColumn.ColumnName;
                cityLabeledComboBoxInput.DataSource = dictionaryData1.Cities;
                cityLabeledComboBoxInput.DisplayMember = dictionaryData1.Cities.NameColumn.ColumnName;
                cityLabeledComboBoxInput.ValueMember = dictionaryData1.Cities.CitiesIDColumn.ColumnName;

有没有办法从这两个表中显示名称?

也许在 sql 中添加另一列(原文如此!)?

【问题讨论】:

    标签: c# winforms sql-server-2005 dataset


    【解决方案1】:

    使用ComboBox的Format事件,找到item的父行,设置事件arg的Value属性。

    void comboBox_Format(object sender, ListControlConvertEventArgs e) { DataRowView cityRow = e.ListItem as DataRowView; string city = cityRow["name"].ToString(); DataRow countryRow = cityRow.Row.GetParentRow("parentRelation"); string country = countryRow["name"].ToString(); e.Value = city + " " + country; }

    或者您可以在城市表中添加一列,并将表达式属性设置为父关系并显示它。

    【讨论】:

      【解决方案2】:

      使用类似于以下 SQL 的内容作为数据集的数据源:

      SELECT City.ID, City.Name + ", " + Country.Name AS CityCountry
      FROM Cities City
         INNER JOIN Countries Country ON City.CountryID = Country.CountryID
      

      另一个选项与上面类似,但会提供一些额外的可重用性:从上面的 SQL 创建一个视图。

      【讨论】:

      • 它生成错误 Dynamic SQL generation is not supported against multiple base tables 。我想我必须专注于组合框功能:/
      • 那么我建议使用上面的 SQL 创建一个视图。您应该能够从该视图创建一个简单的数据集(无论您如何实例化它)。
      【解决方案3】:

      使用这样的查询作为您的数据源,尽管这对您的 DAL 有很多假设。

      select Countries.Code + '.' + cast(Cities.ID as varchar(15)) as ValueMember, 
             Cities.Name + ', ' + Countries.Name
      from ...
          inner join ...
      

      【讨论】:

      • 它生成错误 Dynamic SQL generation is not supported against multiple base tables 。我想我必须专注于组合框功能:/
      猜你喜欢
      • 2014-03-16
      • 1970-01-01
      • 2018-12-26
      • 2016-04-23
      • 2018-06-20
      • 2010-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多