【问题标题】:How to populate combobox from database C#?如何从数据库 C# 填充组合框?
【发布时间】:2012-10-08 04:35:14
【问题描述】:

我想用数据库中的名称填充我的组合框。是否有可能在 1 个组合框中填充 2 列?例如:我有 2 列,NamePosition。我想把名字放在对应位置的combobox中。

示例:

Name                        Position
---------------------------------------------
jack                        President
jill                        President
maria                       Vice President
john                        Secretary

这是我的代码:

{

        DataTable table = new DataTable();
        using (SqlConnection sqlConn = new SqlConnection("my connection"))

        {

         using (SqlDataAdapter da = new SqlDataAdapter(@"SELECT Name, Position FROM CandidateTable", sqlConn))

         da.Fill(table);

         }

         comboBox1.DataSource = table;

        comboBox1.DisplayMember = "Name";

        comboBox1.ValueMember = "Position";

}

注意:我想用 jack 和 jill 的名字填充我的组合框,因为它们的位置相同。其他名字也在另一个组合框中..不在总统组合框中..我想要一个单独位置的组合框..你懂我的英语吗?

【问题讨论】:

  • 如果您展示了您迄今为止所做的工作,我们可以帮助您。但我们不是免费的编码器。您应该编写自己的代码。

标签: c# database combobox


【解决方案1】:

您需要连接数据库或模型中的两个字段

SELECT (name + ' - ' + Position) AS NameAndPosition from Employee

public class Employee
{
   public string Name {get; set; }
   public string Position {get; set; }

   public string NameAndPosition
   {
      return String.Format("{0} - {1}", Name, Position);//
   }
}

在您的组合框中,显示字段为NameAndPosition

【讨论】:

    【解决方案2】:

    组合框中不可能有两列。但是,有几种可用的 javascript 可以构建一种自定义界面来执行此操作。

    这是其中一个的链接

    http://blog.pengoworks.com/index.cfm/2008/4/3/Preview-jQuery-Multicolumn-Dropdown-Plugin

    另一种选择是,您可以同时选择名称和位置作为一个字段并将其显示在下拉列表中,如

    'select [Name] + " - " + [Position"] from table xxx'
    

    这样,您将在下拉列表中同时拥有姓名和职位。

    【讨论】:

      【解决方案3】:

      使用这个代码,我相信你会得到你的答案......

      string query = "SELECT unitId,unitName FROM unit";
      DataSet ds = new DataSet();
      
      sqlopen();//a function for check open or close sql connection
      
      // you must set already sqlConnection for sqlCon parameter
      SqlCommand cmd = new SqlCommand(query, sqlCon); 
      cmd.CommandType = CommandType.Text;
      SqlDataAdapter da = new SqlDataAdapter(cmd);
      DataSet ds = new DataSet();
      da.Fill(ds, "tbl");
      
      cbEdit.DataSource = ds.Tables["tbl"];
      cbEdit.DisplayMember = "unitName";
      cbEdit.ValueMember = "unitId";
      

      【讨论】:

        猜你喜欢
        • 2012-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多