将DataSet Table分配给Type Control的变量

时间:2014-07-15 09:56:23

标签: c# visual-studio-2010

我对此进行了大量研究但却一无所获

我在表单中有很多ComboBox控件,我需要用DataSet Table中的数据填充它们,如下所示:

foreach (Control ctrl in this.Controls)
{
     if (ctrl.GetType() == typeof(ComboBox))
     {
        clsMasterFunc.TableName = ctrl.Text;
        dsMasterList = clsMasterFunc.select();

        ctrl.DataSource = dsMasterList.Tables[0];
     }
}

但是,我收到以下错误

'System.Windows.Forms.Control' does not contain a definition for 'DataSource' and no extension method 'DataSource' accepting a first argument of type 'System.Windows.Forms.Control' could be found (are you missing a using directive or an assembly reference?)   

在这种情况下如何使用DataSource属性?

2 个答案:

答案 0 :(得分:0)

您的问题是ctrl在该迭代中属于Control类型。是的,它是typeof(Combobox),但你没有把它投射到适当的控制。

您可以通过多种方式实现:

尝试使用ofType:

  this.Controls.OfType<ComboBox>().ToList().ForEach(c =>
  {
      c.DataSource = dsMasterList.Tables[0];
   });

它将作为组合框输入lambda表达式,因此不需要使用OfType进行强制转换。

您还可以将控件转换为Combobox以使DataSource属性可用:

 ComboBox combo = (ComboBox) ctrl;
 combo.DataSource =  dsMasterList.Tables[0];

这是一行:

 ((ComboBox)ctrl).DataSource = dsMasterList.Tables[0];

答案 1 :(得分:0)

ctrlControl类型的变量,因此DataSource属性不可用。 DataSource可以使用ComboBox属性。像这样将ctrl投射到ComboBox

((ComboBox)ctrl).DataSource = dsMasterList.Tables[0];

所以你的代码变成了

foreach (Control ctrl in this.Controls)
{
     if (ctrl.GetType() == typeof(ComboBox))
     {
        clsMasterFunc.TableName = ctrl.Text;
        dsMasterList = clsMasterFunc.select();

        ((ComboBox)ctrl).DataSource = dsMasterList.Tables[0];
     }
}
相关问题