[英]Why am I getting strange ComboBox behavior?
我的打印菜单中有一个comboBox,它允许用户设置打印DPI。 而不是将SelectedIndex的计数从0开始,我必须将其从-1开始以使comboBox返回正确的值。 为什么会这样? 我从这里尝试了一些建议,包括设置默认的SelectedIndex值,但这并没有解决问题。
private void toolStripComboBoxPrint_Click(object sender, EventArgs e)
{
if (toolStripComboBoxPrint.SelectedIndex == -1) dpi = 96;
if (toolStripComboBoxPrint.SelectedIndex == 0) dpi = 200;
if (toolStripComboBoxPrint.SelectedIndex == 1) dpi = 300;
if (toolStripComboBoxPrint.SelectedIndex == 2) dpi = 600;
label1.Text = Convert.ToString(dpi);
}
private void printPreviewToolStripMenuItem_Click(object sender, EventArgs e)
{
if (pictureBoxMain.Image != null)
{
label2.Text = Convert.ToString(dpi);
Bitmap myBitmap = (Bitmap)pictureBoxMain.Image;
myBitmap.SetResolution(dpi, dpi);
printDocument1.DocumentName = myBitmap.ToString();
printDialog1.Document = printDocument1;
printPreviewDialog1.Document = printDialog1.Document;
printPreviewDialog1.ShowDialog();
}
}
当我从-1开始计数时,Label1和Label2仅返回正确的值。 为什么?! 谢谢
请在此处阅读有关ComboBox.SelectedIndex
属性的信息 :
此属性指示组合框列表中当前所选项目的从零开始的索引。 设置新索引将引发
SelectedIndexChanged
事件。SelectedIndex
,SelectedValue
和FormattingEnabled
如下相关:
- 如果
FormattingEnabled
为false
,则在SelectedValue
为空白时, 不会将SelectedIndex
设置为-1 。- 如果
FormattingEnabled
是true
,SelectedIndex
将被设置为-1时SelectedValue
是空白 。
因此,如果您的问题是为什么我的SelectedIndex
值是-1
?
这是因为SelectedValue
为“空白”,并且您将FormattingEnabled
设置为true
。
但是看来您的问题是由于您绑定到错误事件(即OnClick
事件)而不是SelectedIndexChanged
事件这一事实引起的。
发生的是,在组合框的SelectedIndex
属性更改之前,将调用Click
事件处理程序。 因此,您正在查看其旧值。
要解决此问题,请删除toolStripComboBoxPrint_Click
事件处理程序,并将其替换为
private void toolStripComboBoxPrint_SelectedIndexChanged(
object sender,
System.EventArgs e)
{
var selectedIndex = toolStripComboBoxPrint.SelectedIndex;
if (selectedIndex >= 0)
{
if (selectedIndex == 0) dpi = 96;
if (selectedIndex == 1) dpi = 200;
if (selectedIndex == 2) dpi = 300;
if (selectedIndex == 3) dpi = 600;
label1.Text = Convert.ToString(dpi);
}
else // no dpi selected, what to do?
{
// You will need to figure out what you want to do here.
label1.Text = ""; // Empty?
}
}
像这样构造表单时,将此事件处理程序绑定到您的组合框实例:
this.toolStripComboBoxPrint.SelectedIndexChanged +=
new System.EventHandler(toolStripComboBoxPrint_SelectedIndexChanged);
您可以从它们的值中获取组合框。 所选索引从0开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.