C# 将数据源与文本框一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1383609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:54:10  来源:igfitidea点击:

Using a DataSource with a TextBox

c#textboxdatasource

提问by Ben Hymers

I normally program in C++, so all this DataSource/DataSet/Binding stuff is confusing the hell out of me. Hopefully you guys can help.

我通常用 C++ 编程,所以所有这些数据源/数据集/绑定的东西都让我感到困惑。希望大家能帮帮忙。

Basically I'm writing an editor for an XML-based file format (specifically, OFX, for financial data). I've used xsd.exe on my schema to deserialise loaded files into nice, plain old classes. I discovered DataGridView, which is brilliant, which I can just set its DataSource property to one of the collections I'm interested in (specifically, the list of transactions), and when I poke around with the values these changes get reflected in the loaded deserialised file, which I can then serialise out on save. But when I want to 'map' just a simple string to a TextBox (e.g. the account number), I can't use this clever method at TextBoxes don't seem to have a DataSource member... Using their 'Text' property just sets the text once and doesn't reflect changes back to the underlying object, so saving has to grab the values from the control first. I'd like it to be automatic like for the DataGridView.

基本上,我正在为基于 XML 的文件格式(特别是 OFX,用于财务数据)编写一个编辑器。我在我的架构上使用 xsd.exe 将加载的文件反序列化为漂亮的、普通的旧类。我发现了 DataGridView,它非常棒,我可以将它的 DataSource 属性设置为我感兴趣的集合之一(特别是事务列表),当我查看这些值时,这些更改会反映在加载的反序列化的文件,然后我可以在保存时将其序列化。但是,当我只想将一个简单的字符串“映射”到 TextBox(例如帐号)时,我无法在 TextBox 上使用这种巧妙的方法似乎没有 DataSource 成员...使用它们的“Text”属性只设置一次文本并且不会将更改反映回底层对象,所以保存必须首先从控件中获取值。我希望它像 DataGridView 一样是自动的。

I've tried fiddling with the DataBindings but I have no idea what to use as the propertyName or dataMember, so I'm not sure if that's what I'm meant to be using:

我试过摆弄 DataBindings,但我不知道用什么作为 propertyName 或 dataMember,所以我不确定这是否是我打算使用的:

accountNumberTextBox.DataBindings.Add(new Binding("???", myDocument.accountNumber, "???");

Am I missing something really obvious? I hope so!

我错过了一些非常明显的东西吗?但愿如此!

采纳答案by Kent Boogaart

What you're missing is that strings are immutable in .NET. Thus, for a binding to make any sense the stringvalue needs to be encapsulated by something else. The data binding system then replacesthe existing string with a new one when the user enters a value.

您缺少的是strings 在 .NET 中是不可变的。因此,要使绑定有意义,string值需要被其他东西封装。当用户输入一个值时,数据绑定系统然后用一个新的字符串替换现有的字符串。

The something else that encapsulates the stringcan be a DataTableor a plain old class that includes change notification. The best way to provide this change notification is to implement the INotifyPropertyChangedinterface.

封装 的其他东西string可以是DataTable包含更改通知的一个或一个普通的旧类。提供此更改通知的最佳方式是实现该INotifyPropertyChanged接口。

For example:

例如:

public class Document : INotifyPropertyChanged
{
    private string _accountNumber;

    public string AccountNumber
    {
        get { return _accountNumber; }
        set
        {
            if (_accountNumber != value)
            {
                _accountNumber = value;
                //this tells the data binding system that the value has changed, so the interface should be updated
                OnPropertyChanged("AccountNumber");
            }
        }
    }

    //raised whenever a property value on this object changes. The data binding system attaches to this event
    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged:

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

So, your data binding hook-up would look like this:

因此,您的数据绑定连接将如下所示:

var document = ...; //get document from somewhere
//bind the Text property on the TextBox to the AccountNumber property on the Document
textBox1.DataBindings.Add("Text", document, "AccountNumber");

回答by adatapost

accountNumberTextBox.DataBindings.Add("Text",
                                      myDocumnt.Tables["your_table"],
                                      "table_field");

Example,

例子,

DataSet ds = new DataSet("DB");
DataTable dt = new DataTable("myTable");
dt.Columns.Add("Name");
dt.Rows.Add("PP");
dt.Rows.Add("QQ");
ds.Tables.Add(dt);

textBox1.DataBindings.Add("Text", ds.Tables["myTable"], "Name");