c# InvalidCastException只适用于一个值
本文关键字:一个 InvalidCastException 适用于 | 更新日期: 2023-09-27 18:18:38
我有一个datagridview,我有一些代码,看看是否有一些下拉菜单已经改变。
private void tbl_TransactionsDataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox combo = e.Control as ComboBox;
if (combo != null && tbl_TransactionsDataGridView.CurrentCell.ColumnIndex == 3)
{
// Remove an existing event-handler, if present, to avoid
// adding multiple handlers when the editing control is reused.
combo.SelectedIndexChanged -=
new EventHandler(ComboBox_SelectedIndexChanged);
// Add the event handler.
combo.SelectedIndexChanged +=
new EventHandler(ComboBox_SelectedIndexChanged);
}
if (combo != null && tbl_TransactionsDataGridView.CurrentCell.ColumnIndex == 6)
{
// Remove an existing event-handler, if present, to avoid
// adding multiple handlers when the editing control is reused.
combo.SelectedIndexChanged -=
new EventHandler(Status_SelectedIndexChanged);
// Add the event handler.
combo.SelectedIndexChanged +=
new EventHandler(Status_SelectedIndexChanged);
}
}
当ColumnIndex为6时,它跳转到以下代码。令人恼火的是,这对我从下拉菜单中选择的任何值都有效,除了1。如果我选择1,就会得到InvalidCastException,告诉我需要使用一个小于无穷大的数字。如果我选择任何其他数字,一切都会按预期的方式启动。我做错了什么?
private void Status_SelectedIndexChanged(object sender, EventArgs e)
{
object oStatus = new object();
oStatus = ((ComboBox)sender).SelectedValue;
if (!Convert.IsDBNull(oStatus))
{
SendKeys.Send("{TAB}");
if (Convert.ToInt32(oStatus) != 1)
{
tbl_TransactionsDataGridView.CurrentRow.Cells["CheckInEmployee"].Value = Environment.UserName;
tbl_TransactionsDataGridView.CurrentRow.Cells["CloseDate"].Value = DateTime.Now;
}
if (Convert.ToInt32(oStatus) == 1)
{
tbl_TransactionsDataGridView.CurrentRow.Cells["CheckOutEmployee"].Value = Environment.UserName;
tbl_TransactionsDataGridView.CurrentRow.Cells["CheckInEmployee"].Value = null;
tbl_TransactionsDataGridView.CurrentRow.Cells["CloseDate"].Value = null;
}
}
}
您的意思是使用ComboBox.SelectedValue
吗?这涉及到数据绑定,我不知道你绑定的是什么。
如果您只是将int
s添加到ComboBox.Items
集合中,则使用SelectedItem
。这个属性也可以返回null
…注意,对于null
输入,Convert.IsDBNull
返回false
。看到这里。
最后,将Convert
转换为Int32
,如下:
private void Status_SelectedIndexChanged(object sender, EventArgs e)
{
object oStatus = new object();
oStatus = ((ComboBox)sender).SelectedItem;
if (oStatus != null && !Convert.IsDBNull(oStatus))
{
SendKeys.Send("{TAB}");
if (((int)oStatus) != 1)
{
tbl_TransactionsDataGridView.CurrentRow.Cells["CheckInEmployee"].Value = Environment.UserName;
tbl_TransactionsDataGridView.CurrentRow.Cells["CloseDate"].Value = DateTime.Now;
}
else
{
tbl_TransactionsDataGridView.CurrentRow.Cells["CheckOutEmployee"].Value = Environment.UserName;
tbl_TransactionsDataGridView.CurrentRow.Cells["CheckInEmployee"].Value = null;
tbl_TransactionsDataGridView.CurrentRow.Cells["CloseDate"].Value = null;
}
}
}
或者,您也可以使用ComboBox.SelectedIndex
。