且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Windows窗体应用程序中绑定combox

更新时间:2023-12-06 10:19:40

如果在该行上出现此错误,请将其转换为:



If you get this error on that line, convert it to:

if(cmbPartyTypeType.SelectedValue != null && cmbPartyTypeType.SelectedValue.ToString() == "1")
...





但是,更方便的方法是使用调试器。在您怀疑错误之前放置断点(使用F9)。然后运行您的应用程序当调试器到达断点时,按F10逐步执行。

通过使用调试器,您可以自己找到答案,我向您保证,与等待其他人的答案相比,您可以更快地找到答案。



[更新]





But, much more convenient way is to use the debugger. Put a breakpoint (with F9) before where you suspect the error. Then run your application. When the debugger hits the breakpoint, go step by step by pressing F10.
By using the debugger, you can find your answer by yourself, and I assure you, you can find it faster compared to waiting for an answer from someone else.

[updated]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Test_Cmb
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            InitOthers();
        }

        BindingSource bs = new BindingSource();

        private void InitOthers()
        {
            this.bs.DataSource = typeof(MyComboItem);
            this.bs.Add(new MyComboItem()
            {
                DisplayVal = "Select",
                SelectedVal = "0"
            });
            this.bs.Add(new MyComboItem()
            {
                DisplayVal = "Agent",
                SelectedVal = "1"
            });

            this.comboBox1.DisplayMember = "DisplayVal";
            this.comboBox1.ValueMember = "SelectedVal";
            this.comboBox1.SelectedValueChanged += comboBox1_SelectedValueChanged;

            this.comboBox1.DataSource = this.bs;
        }

        void comboBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            this.textBox1.Text = this.comboBox1.SelectedValue == null ?
                "null value" : this.comboBox1.SelectedValue.ToString();

        }
    }

    public class MyComboItem
    {
        public string DisplayVal { get; set; }
        public string SelectedVal { get; set; }
    }
}