组合框选择项目 [英] combobox selected item

查看:81
本文介绍了组合框选择项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将一个表单的combobox selectedItem(连接)转换为另一个表单(Form1)



i试过:

1) in connect:form

< pre lang =   c#> public  string  machineId 
{
get
{
return comboBox1.SelectedItem.ToString();
}
set
{
comboBox1.Text = value ;
}}



和Form1:

< pre lang =   c#>连接c =  new  Connect() ; 
String machineid = c.machineId;







但是它给出了空引用异常。





2)

在Connect表单中



combox - > Public

和Form1:



< pre lang =C#>连接c = new Connect();
字符串 machineid = c.comboBox1.SelectedItem.ToString(); < / pre > < / pre >





尽管它返回空值

解决方案

答案很简单:一个ComboBox在创建(实例化)时,其'SelectedItem属性设置为Null。您可以通过将此代码放入代码并设置断点,并在执行此代码行后检查变量中的值来验证这一点:

 对象 defaultComboBoxSelectedItem = comboBox1.SelectedItem; 

因此,您有一些选择:您可以在创建表单时设置ComboBox的'SelectedItem属性,然后 您尝试访问它,或者,您可以在另一个表格中更改代码中的位置,其中访问ComboBox的SelectedItem的值。



使用第一个选项,您实际上在ComboBox中提供默认选择:这可能非常合适,或者不合适:取决于上下文。



或者,您可以测试SelectedItem == null,并且只返回一些表示其null的字符串值,如果值为null。



您所做的选择取决于您的应用程序以及它们之间的预期交互你想要呈现的两个表格。


在这里查看我过去的答案,

从C#中的另一个表单调用ComboBox [ ^ ]



-KR


how to get the combobox selectedItem of one form(connect)into another form(Form1)

i Was tried:
1)in connect:form

<pre lang="c#">public string machineId
        {
            get
            {
                return comboBox1.SelectedItem.ToString();
            }
            set
            {
                comboBox1.Text = value;
            }}


and in Form1:

<pre lang="c#">Connect c = new Connect();
                String machineid=c.machineId;




but it's giving nullreference exception.


2)
In Connect form

combox-->Public
and in Form1:

Connect c = new Connect();
                String machineid=c.comboBox1.SelectedItem.ToString();</pre></pre>



eventhough it's returning null value

解决方案

The answer is very simple: a ComboBox, when it is created (instantiated), has its 'SelectedItem Property set to Null. You can verify this by putting this in your code, and setting a break-point, and examining the value in the variable after this line of code executes:

object defaultComboBoxSelectedItem = comboBox1.SelectedItem;

So, you have some choices to make: you can set the 'SelectedItem Property of the ComboBox when the Form is created, and before you try and access it, or, you can change the place in your code in the other Form where the value of ComboBox 'SelectedItem is accessed.

With the first choice, you, in essence, supply a default selection in the ComboBox: that may be very appropriate, or not appropriate: depends on the context.

Or, you can test for SelectedItem == null, and only return some string value that will indicate its null, if the value is null.

The choice you make will depend on your Application, and the intended interaction between your two Forms you wish to present.


Check my past answer here,
Call ComboBox from another form in C#[^]

-KR


这篇关于组合框选择项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆