【问题标题】:How to retrieve data from SQL into a textbox using Binding?如何使用绑定将数据从 SQL 检索到文本框中?
【发布时间】:2020-11-11 14:09:06
【问题描述】:

这是我的模特:

public class ComplaintModel
{
    public string CustomerName { get; set; }

    public string ValuesFromSalesOrder
    {
        get
        {
            return  CustomerName;
        }
    }

}

这是我运行查询以从 SQL 获取数据的地方:

    public class DataAccess
    {
        public List<ComplaintModel> FindOrderNumber(string _OrderNumber)
        {
            using(SqlConnection conn = new SqlConnection(ConnectionString.MJMconnString))
            {
                var output = conn.Query<ComplaintModel>($"SELECT c.name FROM SalesOrder so JOIN Customer c ON so.customerID = c.id WHERE so.number = ' {_OrderNumber} '").ToList();
                return output;

            }
        }
     }

最后,我在这里尝试将 SQL 的返回值显示到 TextBox...

public Complaints_Form()
{
    InitializeComponent();
   
}

private void UpdateBinding()
{
    customer_name.DataBindings.Add("Text", orderNumb, "ValuesFromSalesOrder"); // This is the textbox
}

List<ComplaintModel> orderNumb = new List<ComplaintModel>();

private void searchButton_Click(object sender, EventArgs e)
{
    DataAccess db = new DataAccess();

    orderNumb = db.FindOrderNumber(orderNumber.Text);


    UpdateBinding();
}

问题

第一次尝试单击Search Button - 没有任何反应,CustomerName 文本框没有更新。

我第二次点击Search Button - 我得到这个错误:System.ArgumentException: 'This causes two bindings in the collection to bind to the same property. Parameter name: binding'

我已经在 SQL Server 中测试了查询 - 它肯定会返回一个值。

我哪里错了?以及如何让它发挥作用。

研究

我用过这个答案

【问题讨论】:

标签: c#


【解决方案1】:

每次单击按钮时,您都会添加一个新绑定。您应该只添加一次绑定。当源值更改时,您不会更新绑定。创建绑定后,它将捕获对其绑定的对象或值的任何更改,并根据需要反映该更改。

在表单构造函数中添加绑定,在按钮单击处理程序中删除UpdateBinding 方法和对其的调用。您还需要将orderNumb 设置为表单上的字段,而不是按钮单击处理程序中的私有变量。

【讨论】:

    【解决方案2】:

    好的,我注意到了问题所在。

    这里:

    using(SqlConnection conn = new SqlConnection(ConnectionString.MJMconnString))
    {
        var output = conn.Query<ComplaintModel>($"SELECT c.name FROM SalesOrder so JOIN Customer c ON so.customerID = c.id WHERE so.number = ' {_OrderNumber} '").ToList();
        return output;
    }
    

    查询的这个特定部分:SELECT c.name

    我需要将其更改为:SELECT c.name as CustomerName 注意额外的部分as CustomerName

    然后这会链接到我的模型public string CustomerName { get; set; }

    现在它完全可以工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-28
      • 2014-03-31
      • 2012-07-09
      • 2022-08-02
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      相关资源
      最近更新 更多