【问题标题】:c# use combobox value in LINQc# 在 LINQ 中使用组合框值
【发布时间】:2017-09-22 17:33:16
【问题描述】:

我正在使用以下代码使用 LINQ 和实体框架在 datagridview 中生成组合框列。

dgvLoadTable.DataSource = null;
var context = new BatchEntities(); 
var TableName = cboSelectTable.Text.ToString();
var rawData = context.GetType().GetProperty(TableName).GetValue(context, null);
var truncatedData = ((IQueryable<object>)rawData).Take(0);
var source = new BindingSource { DataSource = truncatedData };

dgvLoadTable.DataSource = source;
dgvLoadTable.ReadOnly = false;
dgvLoadTable.AllowUserToAddRows = true;

var practices = (from p in context.TABLE1 select p.PRACTICE).Distinct();

for(int r= 0; r < dgvLoadTable.Rows.Count; r++)
{
    for(int c = 0; c < dgvLoadTable.Columns.Count; c++)
    {
        if(c == 2 || c == 4)
        {
            this.dgvLoadTable[c, r] = new DataGridViewComboBoxCell();
            foreach(var name in practices)
                ((DataGridViewComboBoxCell)dgvLoadTable[c, r]).Items
                                                              .AddRange(practices.ToArray());
        }
    }
}
dgvLoadTable.Refresh();

在这里,在 for 循环中,我正在使用 var 实践设置组合框的项目,但对于不同的列,项目会有所不同。这样,我必须为每一列创建不同的变量。有没有办法使用通用代码来执行此操作,其中 tablename 将从 cboSelectTable 中选择,并且该列将按 if 语句中所述的索引选择。如果可能,请提供帮助,谢谢。

【问题讨论】:

  • WinForms、WebForms、WPF 还是其他?
  • 你为什么在practices 上做一个foreach 只是为了做一个AddRange(practices)?似乎应该只是 AddRange 没有 foreachforeachAdd(name)

标签: c# linq datagridview combobox entity-framework-4


【解决方案1】:

您可以使用以下代码插入 Checkboxrow:

代码

            DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn();
            dataGridView1.Columns.Add(chk);
            chk.HeaderText = "Check Data";
            chk.Name = "chk";
            dataGridView1.Rows[2].Cells[3].Value = true;

通常您使用“CurrentCell”方法调用单元格...例如:

代码

private void dgvLoadTable_CelldoubleClick(object sender, DataGridViewCellEventArgs e)
    {
       //do some code here
        if (e.ColumnIndex == 1) // Check the current ColumnIndex...
        {
            //do some code here

        }

所以你不能为每一行设置一个变量。我希望这对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多