0

如何将值从选定字段 (LINQ) 传递到 winforms 中的文本框?

如果是单个字段,我只是这样做

   var result = from row in dtValueBranch.AsEnumerable()
                         where row.Field<int>("branchID") == idBranch
                         select row.Field<string>("branchName");

        StringBuilder sb = new StringBuilder();

        foreach (string s in result)
        {
            sb.Append(s + Environment.NewLine);
        }

        tbBranch.Text = sb.ToString();

所以这是许多领域的代码 LINQ

    var result = from row in dtValueBranch.AsEnumerable()
                 where row.Field<int>("branchID") == idBranch
                 select new
                 {
                      BranchName = row["branchName"].ToString(),
                      branchTel = row["branchTel1"].ToString(),
                      // And many more fields

                 };

如何将每个字段实现到每个文本框?

4

2 回答 2

3

请记住,您的结果查询可能有多行,您的问题似乎集中在如何访问一行的字段上。你可以这样做:

var row = result.First();  // select first row of results

textbox1.Value = row.BranchName;
textbox2.Value = row.branchTel;
// etc..

查询中的select new语法在结果枚举中创建了一个匿名类型。您不能按名称引用该类型,但如果您使用var声明样式并让编译器进行类型推断,则可以创建局部变量(如行)。

如果您想将所有行中一个字段的所有值塞进一个文本框(如在您的第一个代码示例中),您可以执行以下操作:

    StringBuilder sbBranch = new StringBuilder();
    StringBuilder sbBranchTel = new StringBuilder();
    // etc

    foreach (var row in result)
    {
        sbBranch.Append(row.BranchName);
        sbBranch.Append(Environment.NewLine);
        sbBranchTel.Append(row.branchTel);
        sbBranchTel.Append(Environment.NewLine);
        // etc
    }

    tbBranch.Text = sbBranch.ToString();
    tbBranchTel.Text = sbBranchTel.ToString();
    // etc

However, if you're wanting to display multiple rows of multiple fields of data, you might want to look at using a data grid control instead of a herd of textboxes. You'll save yourself a lot of effort, and your users will probably thank you too.

于 2012-11-02T17:10:07.130 回答
1

你可以这样做:

var rows = dtValueBranch.AsEnumerable()
                        .Where(row => row.Field<int>("branchID") == idBranch);

textBox1.Value = string.Join(Environment.NewLine, 
                           rows.Select(row => row.Field<string>("branchName"));

textBox2.Value = string.Join(Environment.NewLine, 
                           rows.Select(row => row.Field<string>("branchTel1"));
于 2012-11-02T17:03:08.867 回答