本人的想法是点击button2后,可以鼠标点选东西,然后显示在combobox上,可是为什么现在点击按钮后,combobox空白,然后再嗯一下按钮才会在combobox上显示鼠标点选的东西呢?
private void button2_Click(object sender, EventArgs e) // 机器时间鼠标点击选择
{
comboBox1.Items.Clear();
IvcSelection Selection = app.findSelection("Component");
if (Selection.ItemCount == 0)
{
return;
}
if (Selection.ItemCount >= 1)
{
for (int i = 0; i < Selection.ItemCount; i++)
{
comp = (IvcComponent)Selection.getItem(i);
for (int a = 0; a < comp.PropertyCount; a++)
{
object name = comp.getProperty("Name");
string propName = comp.getPropertyName(a);
object propValue = comp.getProperty(propName);
comboBox1.Items.Add(name + "::" + propName + "::" + propValue);
}
}
}
}
解决方案
40
private void button2_Click(object sender, EventArgs e) // 机器时间鼠标点击选择
{
comboBox1.Items.Clear();
IvcSelection Selection = app.findSelection("Component");
// if (Selection.ItemCount == 0)
// return;
// 已经有了 count 判断,所以不需要再判断 >= 1 了,再说 >= 1 和 > 0 在这里貌似没什么区别
// 其实这里倒是应当判断下 Selection 能否为 null
if (Selection == null)
return;
// 假如 ItemCount == 0 则不会执行循环,所以上面的 ItemCount 判断是多余的
for (int i = 0; i < Selection.ItemCount; i++)
{
comp = (IvcComponent)Selection.getItem(i);
if (comp == null)
continue;
for (int a = 0; a < comp.PropertyCount; a++)
{
// 利用格式化字符串
string item = string.Format("{0}::{1}::{2}",
comp.getProperty("Name"), comp.getPropertyName(a), comp.getProperty(propName));
comboBox1.Items.Add(item);
}
if(comboBox1.Items.Count > 0)
comboBox1.SelectedIndex = 0; // 由于前面 Items.Clear() 了,所以 SelectedIndex = -1; 所以需要指定被选择的索引为 0
}
}