【问题标题】:How to bind this source variable to an existing textbox?如何将此源变量绑定到现有文本框?
【发布时间】:2019-12-04 02:23:20
【问题描述】:

美好的一天!我最近在微软网站上发现了这个。

// Create the list to use as the custom source. 
            var source = new AutoCompleteStringCollection();
            source.AddRange(new string[]
                    {
                        "January",
                        "February",
                        "March",
                        "April",
                        "May",
                        "June",
                        "July",
                        "August",
                        "September",
                        "October",
                        "November",
                        "December"
                    });


            // Create and initialize the text box.
            var textBox = new TextBox
            {
                AutoCompleteCustomSource = source,
                AutoCompleteMode =
                    AutoCompleteMode.SuggestAppend,
                AutoCompleteSource =
                    AutoCompleteSource.CustomSource,
                Location = new Point(20, 20),
                Width = ClientRectangle.Width - 40,
                Visible = true
            };

            // Add the text box to the form.
            Controls.Add(textBox);

它的作用是创建一个字符串集合和一个新的文本框。我只是想知道是否有办法将此源绑定到现有文本框而不是创建新文本框。我尝试了以下代码,但它不起作用。

            txtTo.AutoCompleteCustomSource = source;
            txtTo.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            txtTo.AutoCompleteSource = AutoCompleteSource.CustomSource;

【问题讨论】:

  • 它应该可以工作。你把你的代码放在哪里了?在 Form_Load 中?
  • 运行代码时会发生什么?是否发生异常?在任何情况下,您都可以将代码放在构造函数或 OnLoad 事件中,就是这样,确保在您的代码之前首先调用 InitializeComponent();,因为这将初始化您的 TextBox 控件。
  • CustomSourceCompleteMode之前尝试txtTo.AutoCompleteSource = AutoCompleteSource.CustomSource这一行
  • @rjs123431 是的,我把它放在了 Form_Load 事件中。
  • @MichaelBalser 代码有效。我的问题是我是否可以将源变量绑定到现有文本框而不是创建新文本框。

标签: c# winforms autocomplete textbox


【解决方案1】:

这是有效的:

    private void Form1_Load(object sender, EventArgs e)
    {
        var source = new AutoCompleteStringCollection();

        source.AddRange(new string[]
                {
                    "January",
                    "February",
                    "March",
                    "April",
                    "May",
                    "June",
                    "July",
                    "August",
                    "September",
                    "October",
                    "November",
                    "December"
                });

        txtTo.AutoCompleteCustomSource = source;
        txtTo.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
        txtTo.AutoCompleteSource = AutoCompleteSource.CustomSource;

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 2020-01-03
    • 2011-05-19
    • 2014-03-27
    相关资源
    最近更新 更多