我的print菜单中有一个comboBox,允许用户设置print DPI。为了让comboBox返回正确的值,我必须从-1开始计算SelectedIndex计数,而不是从0开始。为什么会发生这种情况?我尝试了这里的一些建议,包括设置默认的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只返回正确的值。为什么?!谢谢
发布于 2015-04-18 16:13:24
请阅读有关ComboBox.SelectedIndex
属性here的信息
此属性指示组合框列表中当前选定项的从零开始的索引。设置新索引将引发
SelectedIndexChanged
事件。SelectedIndex
、SelectedValue
和FormattingEnabled
的关系如下:
如果FormattingEnabled
为false
,则当SelectedValue
为空白时,SelectedIndex
不会被设置为-1\f25-1。-1\f25
FormattingEnabled
为-1\f25 true
-1\f6,当-1\f25 SelectedValue
-1\f6为-1\f25 blank.
-1\f6时,-1\f25 SelectedIndex
-1\f6将被设置为-1\f25-1\f6
因此,如果您的问题是为什么我的SelectedIndex
值是-1
这是因为SelectedValue
是“空的”,而您将FormattingEnabled
设置为true
。
但是,您的问题似乎是由于您绑定到了错误的事件,即OnClick
事件,而不是SelectedIndexChanged
事件。
发生的情况是,在组合框的SelectedIndex
属性更改之前,您的SelectedIndex
事件处理程序被称为。因此,您看到的是它的旧值。
要解决此问题,请删除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?
}
}
并将此事件处理程序绑定到您的combobox实例,当您的窗体构造如下:
this.toolStripComboBoxPrint.SelectedIndexChanged +=
new System.EventHandler(toolStripComboBoxPrint_SelectedIndexChanged);
发布于 2015-04-18 14:38:35
您可以从它们的值中获取combobox。所选索引从0开始。
https://stackoverflow.com/questions/29713839
复制相似问题