无法从ComboBox

时间:2016-01-14 15:53:02

标签: c# windows forms combobox

我有一个表单(Form1)和一个类(classx)。我在从Form1到classx的comboBox2中读取文本时遇到问题。当我在调试时单击comboBox2中的任何文本时,它会向我显示&#34; o:oo:oo &#34;,就像我没有从comboBox2中点击任何内容。我知道问题在于if()行,因为如果我把它留下: form1.comboBox2.SelectedItem.ToString(),或 form1.comboBox2.SelectedText.ToString()< / strong>,或 form1.comboBox.Text ,或任何其他选项(我在stackoverflow.com和Google中查找过),它仍然显示0:00:00。 但是,如果我这样写:if(&#34; Rome&#34; == Places [i]),它会计算罗马的值,显示 01:07:30 。如何阅读组合框中的文字,这可以在我的代码中使用?

这是我的班级:

public class classx
{        
    public string[] Places = new string[] { "Berlin", "Paris", "London", "Rome", "Tirana", "Istanbul" };
    public int[] Kilometers = new int[] { 50, 30, 70, 110, 40, 90 };
    public TimeSpan Times()
    {
        double length = 0; double hour = 0, minute = 0, seconds = 0; int hour1 = 0, minute1 = 0, second1 = 0;
        Form1 form1 = new Form1();

        for (int i = 0; i <= 5; i++)
        {
            //this is the row which doesn't work
            if (form1.comboBox2.SelectedText.ToString() == Places[i])
            {
                length = Kilometers[i];
            }
        }
        hour = (length / 80);
        hour1 = Convert.ToInt32(Math.Truncate(hour));
        minute = (hour - Math.Truncate(hour)) * 60;
        minute1 = Convert.ToInt32(Math.Truncate(minute));
        second = (minute - Math.Truncate(minute)) * 60;
        second1 = Convert.ToInt32(Math.Truncate(second));
        TimeSpan time = new TimeSpan(Convert.ToInt32(hour), Convert.ToInt32(minute1), Convert.ToInt32(second1));
        TimeSpan TimeLength = new TimeSpan(hour1, minute1, second1);
        return TimeLength;
    }
}

这是我的Form1

 public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

    }

    public void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    public void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        classx duration = new classx();

        MessageBox.Show("From " + comboBox1.Text + " to " + comboBox2.Text + " it takes around " + duration.Times());
    }
}

没有显示错误。知道如何从comboBox2获取文本吗?

编辑:对于有同样问题的未来访问者,这个答案对我有帮助:https://stackoverflow.com/a/34794775/5749161

6 个答案:

答案 0 :(得分:1)

  

我在从Form1读取comboBox2中的文本时遇到问题   分类。

来自classx的代码行:

Form1 form1 = new Form1();

form1classx方法中商品的一部分。然后,只要comboBox2中的public access modifierForm1,您就可以轻松访问它,就像您所做的那样:

form1.comboBox2 //this can be easily done

但这里最大的问题是你在classx中声明了新表单,你的表单构造函数如下所示:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

    }

    public void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    public void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        classx duration = new classx();

        MessageBox.Show("From " + comboBox1.Text + " to " + comboBox2.Text + " it takes around " + duration.Times());
    }
}

请确保在表单初始化中没有为comboBox2选择值。这意味着您的comboBox2始终不会选择任何内容。因此,classx

中也没有任何结果
//this is the row which doesn't work
//it is because nothing is ever selected in the first place
if (form1.comboBox2.SelectedText.ToString() == Places[i])
{
    length = Kilometers[i];
}

如果需要,您可能希望在Form1构造函数中放置选定的索引:

public Form1()
{
    InitializeComponent();
    comboBox2.SelectedIndex = 0; //assuming there is at least 1 item in the comboBox
}

但最好的是来在您的classx中调用表单。这可能是一种浪费。

因此,我建议你这样做反过来:而不是从form1中的方法调用classx,而是应该form1然后在form1中,您拥有classx个实例(比如名为classx classxInstance)。而在classx方法Times()目前您没有收到任何输入。将其更改为接收string输入,您将需要它来接收来自comboBox.SelectedText - &gt;的输入。将其声明为此Times(string input),然后从classxInstance.Times(comboBox2.SelectedText)中将其称为此Form1,事情将会好很多

编辑:

另一种方式看起来像这样,

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

    }

    public void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    public void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        classx duration = new classx();

        //Note that you should not use Text here, but selectedText
        //Note that now your classx takes input from comboBox2.SelectedText    
        MessageBox.Show("From " + comboBox1.SelectedText + " to " + comboBox2.SelectedText + " it takes around " + duration.Times(comboBox2.SelectedText));
    }
}

你的classx看起来像

public class classx
{        
    public string[] Places = new string[] { "Berlin", "Paris", "London", "Rome", "Tirana", "Istanbul" };
    public int[] Kilometers = new int[] { 50, 30, 70, 110, 40, 90 };
    public TimeSpan Times(string input) //note the input string here
    {
        double length = 0; double hour = 0, minute = 0, seconds = 0; int hour1 = 0, minute1 = 0, second1 = 0;
        //Form1 form1 = new Form1(); //you don't need this

        for (int i = 0; i <= 5; i++)
        {
            //this is the row which doesn't work
            if (input == Places[i]) //now you use input here
            {
                length = Kilometers[i];
            }
        }
        hour = (length / 80);
        hour1 = Convert.ToInt32(Math.Truncate(hour));
        minute = (hour - Math.Truncate(hour)) * 60;
        minute1 = Convert.ToInt32(Math.Truncate(minute));
        second = (minute - Math.Truncate(minute)) * 60;
        second1 = Convert.ToInt32(Math.Truncate(second));
        TimeSpan time = new TimeSpan(Convert.ToInt32(hour), Convert.ToInt32(minute1), Convert.ToInt32(second1));
        TimeSpan TimeLength = new TimeSpan(hour1, minute1, second1);
        return TimeLength;
    }
}

答案 1 :(得分:1)

代码中的问题是这一行:

Form1 form1 = new Form1();

您创建表单的新实例并且不对其执行任何操作。这不是同一个实例和已经运行的表单。您基本上使用两种不同的形式。

更改代码如下:

 public TimeSpan Times(string place)
    {
        double length = 0; double hour = 0, minute = 0, seconds = 0; int hour1 = 0, minute1 = 0, second1 = 0;


        for (int i = 0; i <= 5; i++)
        {
            //this is the row which doesn't work
            if (Places[i] == place)
            {
                length = Kilometers[i];
            }
        }
        hour = (length / 80);
        hour1 = Convert.ToInt32(Math.Truncate(hour));
        minute = (hour - Math.Truncate(hour)) * 60;
        minute1 = Convert.ToInt32(Math.Truncate(minute));
        second = (minute - Math.Truncate(minute)) * 60;
        second1 = Convert.ToInt32(Math.Truncate(second));
        TimeSpan time = new TimeSpan(Convert.ToInt32(hour), Convert.ToInt32(minute1), Convert.ToInt32(second1));
        TimeSpan TimeLength = new TimeSpan(hour1, minute1, second1);
        return TimeLength;
    }

然后以您的形式:

private void button1_Click(object sender, EventArgs e)
    {
        classx duration = new classx();
        var result = duration.Times(comboBox1.Text);

        MessageBox.Show("From " + comboBox1.Text + " to " + comboBox2.Text + " it takes around " + result);
    }

答案 2 :(得分:0)

ComboBox.SelectedText已经返回一个字符串,因此不需要使用.ToString()方法。

答案 3 :(得分:0)

你有两个问题。

1)SelectedText永远是&#34;&#34;对于组合框,除非您将其设置为其他内容,因此您需要使用SelectedItem。

2)当您已经在Program类中创建了一个新表单时,您创建了一个新表单。

以下是一个功能齐全的例子。

using System; using System.Windows.Forms;

namespace testforms {
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    } }

不要创建表单,而是让表单创建classx,例如。

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 testforms
{
    public partial class Form1 : Form
    {
        private classx duration = null;
        public Form1()
        {
            InitializeComponent();
            duration = new classx(this);
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            MessageBox.Show("From " + comboBox1.Text + " to " + comboBox2.Text + " it takes around " + duration.Times());
        }
    }

    public class classx 
    {
        public string[] Places = new string[] { "Berlin", "Paris", "London", "Rome", "Tirana", "Istanbul" };
        public int[] Kilometers = new int[] { 50, 30, 70, 110, 40, 90 };

        Form1 form1 = null;

        public classx(Form1 form)
        {
            form1 = form;

            form1.comboBox1.Items.AddRange(Places);
            form1.comboBox2.Items.AddRange(Places);
        }

        public TimeSpan Times()
        {
            double length = 0; double hour = 0, minute = 0, seconds = 0; int hour1 = 0, minute1 = 0, second1 = 0;

            for (int i = 0; i <= 5; i++)
            {
                // change to SelectedItem because selected text will always be "" empty string.
                if (form1.comboBox2.SelectedItem.ToString() == Places[i])
                {
                    length = Kilometers[i];
                }
            }
            hour = (length / 80);
            hour1 = Convert.ToInt32(Math.Truncate(hour));
            minute = (hour - Math.Truncate(hour)) * 60;
            minute1 = Convert.ToInt32(Math.Truncate(minute));
            seconds = (minute - Math.Truncate(minute)) * 60;
            second1 = Convert.ToInt32(Math.Truncate(seconds));
            TimeSpan time = new TimeSpan(Convert.ToInt32(hour), Convert.ToInt32(minute1), Convert.ToInt32(second1));
            TimeSpan TimeLength = new TimeSpan(hour1, minute1, second1);
            return TimeLength;
        }
    }
}

在设计器中将组合框设置为内部,以便可以从classx初始化它们。

namespace testforms
{
    public partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.comboBox1 = new System.Windows.Forms.ComboBox();
            this.comboBox2 = new System.Windows.Forms.ComboBox();
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // comboBox1
            // 
            this.comboBox1.FormattingEnabled = true;
            this.comboBox1.Location = new System.Drawing.Point(36, 30);
            this.comboBox1.Name = "comboBox1";
            this.comboBox1.Size = new System.Drawing.Size(121, 21);
            this.comboBox1.TabIndex = 0;
            // 
            // comboBox2
            // 
            this.comboBox2.FormattingEnabled = true;
            this.comboBox2.Location = new System.Drawing.Point(36, 91);
            this.comboBox2.Name = "comboBox2";
            this.comboBox2.Size = new System.Drawing.Size(121, 21);
            this.comboBox2.TabIndex = 1;
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(36, 162);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 2;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click_1);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 261);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.comboBox2);
            this.Controls.Add(this.comboBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);

        }

        #endregion

        internal System.Windows.Forms.ComboBox comboBox1;
        internal System.Windows.Forms.ComboBox comboBox2;
        private System.Windows.Forms.Button button1;
    }
}

答案 4 :(得分:0)

我改变了

var result = duration.Times(Combo2.Text);

对于所有城市我都有结果,但仅限伦敦我有00:00:00

答案 5 :(得分:-1)

检查一下:

string comboText = comboBox.SelectedValue.ToString();

只是为了表明这是有效的:

类:

public class classzz
{
    public string[] Places;
    public int[] Kilometers;

    public classzz() { 
        Places = new string[] { "Berlin", "Paris", "London" };
        Kilometers = new int[] { 50, 30, 70 };
    }

    public String ShowValues(string text1, int value) {
        return "The values selected were" + text1 + "-" + value.ToString();
    }
}

形式:

public partial class Form1 : Form
{
    protected classzz myClass;

    public Form1()
    {
        InitializeComponent();
        myClass = new classzz();
        comboBox1.DataSource = myClass.Places;
        comboBox2.DataSource = myClass.Kilometers;
    }

    private void button1_Click(object sender, EventArgs e)
    {
       label1.Text = myClass.ShowValues(comboBox1.SelectedValue.ToString(), Int32.Parse(comboBox2.SelectedValue.ToString()));
    }
}