【问题标题】:Combobox default value is always SQL table value - c#组合框默认值始终是 SQL 表值 - c#
【发布时间】:2016-06-29 15:03:37
【问题描述】:

我正在从Stored Procedure 检索datatable,Combobox 正在显示该数据,但我想显示 -Select Program- 作为默认值 Combobox 但它始终显示数据表的第一条记录.

InitializeComponent();
        cbxProgram.Items.Insert(0, "-SELECT PROGRAM-");
        cbxProgram.SelectedIndex = 0;
        cbxProgram.DataSource = SomeBL.GetProgramName().Tables[0];
        cbxProgram.DisplayMember = "ProgramName";

        cbxType.DataSource = SomeBL.GetType("").Tables[0].DefaultView;
        cbxType.DisplayMember = "Type";

        cbxNumber.DataSource = SomeBL.GetNumber("", "").Tables[0].DefaultView;
        cbxNumber.DisplayMember = "Number";

        cbxType.Enabled = false;
        cbxType.Enabled = false;

【问题讨论】:

  • 设置DataSource 将删除组合框中的所有当前项。
  • 在分配DataSource后尝试插入-SELECTED ...。
  • 它给了我一个例外Items collection cannot be modified when the DataSource property is set.
  • @UmmEHabibaSiddiqui 你的SomeBL.GetProgramName().Tables[0]是什么类型的对象?
  • getProgramName 正在返回带有 varchar 值的 datatable

标签: c# winforms stored-procedures combobox default-value


【解决方案1】:

通过使用 Datasource 属性,您首先删除了存在的数据。从数据源填充组合框后,您应该插入“-SELECT PROGRAM-”行。 试试这个:

cbxProgram.DataSource = SomeBL.GetProgramName().Tables[0];
cbxProgram.DisplayMember = "ProgramName";
cbxProgram.Items.Insert(0, "-SELECT PROGRAM-");
cbxProgram.SelectedIndex = 0;

【讨论】:

  • 我在你的代码第一行遇到了异常InvalidArgument=Value of '0' is not valid for 'SelectedIndex'.
  • 这不起作用,因为在设置数据源之后,项目集合受到保护。
  • 有没有办法可以将第一个值作为-Select Program- 从Stored Procedure 发送?
  • @UmmEHabibaSiddiqui 你是对的,我没有注意到你将行设置为 selectedindex,这有点不必要,因为它是一个加载页面。我编辑了代码。
【解决方案2】:

您必须在绑定之前将您的自定义行添加到您的表格中。

我没有对此进行测试,但它应该看起来像这样:

DataTable dt = SomeBL.GetProgramName().Tables[0];
DataRow dr = dt.NewRow();
dr[0] = "-SELECT PROGRAM-";  // Look at the index of your desired column
dt.Rows.InsertAt(dr,0);      // Insert on top position



cbxProgram.DataSource = dt;
cbxProgram.SelectedIndex = 0;
cbxProgram.DisplayMember = "ProgramName";

【讨论】:

    【解决方案3】:

    如果在设置数据源后不允许你添加另一行,你可以考虑将这一行添加到源数据表中。 (我不建议通过更改存储过程从 SQL 数据库中添加它。)

    检查这个伪代码:

    SomeBL.GetProgramName().Tables[0].Rows.Add(new DataRow(0, "-SELECT PROGRAM-"));
    cbxProgram.DisplayMember = "ProgramName";
    cbxProgram.Items.Insert(0, "-SELECT PROGRAM-");
    cbxProgram.SelectedIndex = 0;
    

    【讨论】:

    • 我收到了一个编译时错误Error 1 'System.Data.DataRow' does not contain a constructor that takes 2 arguments
    • 我说的是“伪代码”,它是为那些足够聪明的人准备的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 2012-07-25
    • 2012-04-07
    • 1970-01-01
    相关资源
    最近更新 更多