【问题标题】:ASP.NET LINQ SQL get specific fieldsASP.NET LINQ SQL 获取特定字段
【发布时间】:2011-09-23 14:06:45
【问题描述】:

我正在尝试使用 LINQ - SQL 在 ASP.NET 网页上设置文本框。这是我必须执行选择语句的代码:

    EQCN = Request.QueryString["EQCN"];
    var equipment = from n in db.equipments
                    where n.EQCN.ToString() == EQCN
                    select n;

如何将 TextBox1.text 设置为表格中的特定字段?

非常感谢

编辑

我需要将表格中的每个字段输出到不同的文本框中。因此,对单个人执行查询似乎有点多。一定有办法做到这一点?

谢谢

【问题讨论】:

    标签: c# asp.net linq field


    【解决方案1】:

    你可以选择合适的字段开始:

    EQCN = Request.QueryString["EQCN"];
    var values = from n in db.equipments
                 where n.EQCN.ToString() == EQCN
                 select n.FieldYouWant;
    
    // Or possibly Single, or First...
    var singleValue = values.FirstOrDefault();
    

    认为这就是你所追求的,但如果不是,请澄清你的问题。

    编辑:要回答您的后续问题,您可以使用:

    EQCN = Request.QueryString["EQCN"];
    var query = from n in db.equipments
                 where n.EQCN.ToString() == EQCN
                 select n;
    
    // Or possibly Single, or First...
    var entity = query.Single();
    
    textBox1.Text = entity.Name;
    textBox2.Text = entity.Description;
    textBox3.Text = entity.Title;
    // etc
    

    假设您想要访问实体中的所有内容。如果实体非常大并且您只需要几个字段,您可能想要执行以下操作:

    EQCN = Request.QueryString["EQCN"];
    var query = from n in db.equipments
                 where n.EQCN.ToString() == EQCN
                 select new { n.Name, n.Description, n.Title };
    
    // Or possibly Single, or First...
    var projection = query.Single();
    
    textBox1.Text = projection.Name;
    textBox2.Text = projection.Description;
    textBox3.Text = projection.Title;
    

    我不确定我是否真的将数据访问层和 UI 层如此紧密地耦合在一起,但那是另一回事...

    【讨论】:

      【解决方案2】:

      您只需要执行一次查询,但是一旦完成,您就必须将每个字段分配给一个 TextBox。首先只检索您想要的单个项目:

      EQCN = Request.QueryString["EQCN"];
      var equipment = (from n in db.equipments
                       where n.EQCN.ToString() == EQCN
                       select n).FirstOrDefault();
      

      然后遍历并将每个 TextBox 分配给相应的字段:

      txtName.Text = equipment.Name;
      txtDescription.Text = equipment.Description;
      txtValue1.Text = equipment.Value1;
      txtValue2.Text = equipment.Value2;
      //...
      

      如果您要分配几十个文本框,您可以设置一个自定义控件,该控件可以数据绑定到equipment 对象,但即便如此,您仍然需要为您的控件编写绑定代码。

      我能想到的让这个过程完全自动化的唯一方法是在对象中的一个字段之后命名每个 TextBox,然后使用反射将它们与值匹配:

          var textboxes = Panel1.Controls.OfType<TextBox>();
      
          foreach (TextBox txt in textboxes)
          {
              string fieldname = txt.ID.Remove(0, 3); //"txtDescription" becomes "Description"
      
              string value = equipment.GetType().GetProperty(fieldname).GetValue(equipment, null) as string;
              txt.Text = value;
          }
      

      【讨论】:

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