【问题标题】:Input string was not in a correct format in Visual Studio [duplicate]Visual Studio 中的输入字符串格式不正确[重复]
【发布时间】:2018-01-24 19:44:10
【问题描述】:

尝试在 Visual Studio 中打开我的一个窗口窗体时,我在页面加载之前收到此消息框:“输入字符串的格式不正确”。在该消息框上单击“确定”后,我的页面将正确打开,并且没有显示任何错误。

在我正在加载的窗口窗体上,我有一个 ComboBox 和一个 CheckedListBox,我从 Sql Server 的数据表中获取信息。

问题可能是我在方法中进行的转换吗?如果是这样,如何更改它们以使消息框不再出现。我读过 try parse 会更好,但我不确定如何在这里应用它。

void CheckList_Bikes()
{
    int idcl = Convert.ToInt32(client.SelectedValue.ToString());
    com.Parameters.Clear();
    com.Parameters.AddWithValue("@idclient", idcl);
    adaptb.Fill(biciT);
    bikes.Items.Clear();
    bikes.DataSource = biciT;
    bikes.ValueMember = "ID";
    bikes.DisplayMember = "name";
}

private void client_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        int idcl = Convert.ToInt32(client.SelectedValue.ToString());
        com.Parameters.Clear();
        com.Parameters.AddWithValue("@idclient", idcl);
        bikes.Clear();
        adaptb.Fill(biciT);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

【问题讨论】:

  • 可能是这样的:client.SelectedValue.ToString() 也许看看是否选择了任何东西,然后执行该方法。没有选择 = 什么都不做
  • 如果您在调试模式下运行代码。您将确定您的问题。
  • client 你的ComboBox 吗?你什么时候用数据库中的值填充它们?
  • 是的,客户端是 ComboBox。
  • 您是否调试过代码,该错误意味着您尝试从中解析整数的字符串实际上不包含有效整数。尝试 Int.Parse 或 int.tryParse

标签: c# visual-studio


【解决方案1】:

你可以检查一个项目是否被选中:

void CheckList_Bikes()
{
    if(client.SelectedIndex != -1)
    {
        int idcl = Convert.ToInt32(client.SelectedValue.ToString());
        com.Parameters.Clear();
        com.Parameters.AddWithValue("@idclient", idcl);
        adaptb.Fill(biciT);
        bikes.Items.Clear();
        bikes.DataSource = biciT;
        bikes.ValueMember = "ID";
        bikes.DisplayMember = "name";
    }

}

如果您的格式确实错误,并且您想使用TryParse 来检查转换是否有效,您可以这样做:

void CheckList_Bikes()
{
    int idcl = 0;
    if(Int.TryParse(client.SelectedValue.ToString(), out idcl)
    {
        com.Parameters.Clear();
        com.Parameters.AddWithValue("@idclient", idcl);
        adaptb.Fill(biciT);
        bikes.Items.Clear();
        bikes.DataSource = biciT;
        bikes.ValueMember = "ID";
        bikes.DisplayMember = "name";
    }    
}

编辑:

如果你的字符串中有空格,你可以使用String.Trim 方法去掉它们:

 if(Int.TryParse(client.SelectedValue.ToString().Trim(), out idcl)

【讨论】:

  • TryParse 确实有效,谢谢@Mong Zhu。
  • @Daniel 很高兴听到它有效,但您的格式如何?如果它不允许你解析数字,那么这个解决方案没有多大价值或者我错了吗?=! :) 你的数字字符串中有可能是空格吗?
  • 是的,看来我确实有一些空白空间。
  • @Daniel 你可以使用Trim 去掉空格。检查我的编辑。好运
  • 很高兴知道。 @Mong Zhu 这也可能是题外话,但你能不能看看我提出的这个问题:stackoverflow.com/questions/48396881/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-23
  • 2013-09-20
  • 1970-01-01
  • 2020-05-19
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多