【问题标题】:Int.TryParse passing only boolean value to databaseInt.TryParse 仅将布尔值传递给数据库
【发布时间】:2018-01-20 09:04:32
【问题描述】:

起初我在将数据插入数据库时​​出错。错误是:

“输入的字符串格式不正确”

但后来我使用Int.TryParsestring 转换为int,并且成功了。但我现在面临的问题是 Int.TryParse 只将 1 或 0 之类的布尔值传递给数据库。

例如:如果我在textbox 中写入 34,然后单击确定插入。 textbox 只是将布尔值传递给数据库。 IE; 1 或 0。

谁能帮帮我?任何帮助将非常感激。

这是我的代码:

else{
    try
    {
        conn.Open();

        SqlCommand cmd = new SqlCommand("INSERT INTO ProductServices (ProductCode, ProductStatus, ProductCategory, ProductName, ProductDescription, ProductUnitPrice, ProductCost, ProductPCost, ProductPeck, ProductStock, ProductSWarning, ProductWarehouse, ProductPNotes, ProductImage) VALUES (@ProductCode, @ProductStatus, @ProductCategory, @ProductName, @ProductDescription, @ProductUnitPrice, @ProductCost, @ProductPCost, @ProductPeck, @ProductStock, @ProductSWarning, @ProductWarehouse, @ProductPNotes, @ProductImage)", conn);

        //Save image from PictureBox into MemoryStream object.
        MemoryStream ms = new MemoryStream();
        pictureBoxProduct.Image.Save(ms, ImageFormat.Jpeg);

        //Read from MemoryStream into Byte array.
        Byte[] bytBLOBData = new Byte[ms.Length];
        ms.Position = 0;
        ms.Read(bytBLOBData, 0, Convert.ToInt32(ms.Length));

        SqlParameter[] param = new SqlParameter[14];

        //Create parameter for insert statement.
        param[0] = new SqlParameter("@ProductCode", SqlDbType.NVarChar, 255);
        param[1] = new SqlParameter("@ProductStatus", SqlDbType.NVarChar, 10);
        param[2] = new SqlParameter("@ProductCategory", SqlDbType.NVarChar, 100);
        param[3] = new SqlParameter("@ProductName", SqlDbType.NVarChar, 255);
        param[4] = new SqlParameter("@ProductDescription", SqlDbType.NVarChar, 255);
        param[5] = new SqlParameter("@ProductUnitPrice", SqlDbType.BigInt);
        param[6] = new SqlParameter("@ProductCost", SqlDbType.BigInt);
        param[7] = new SqlParameter("@ProductPCost", SqlDbType.BigInt);
        param[8] = new SqlParameter("@ProductPeck", SqlDbType.NVarChar, 50);
        param[9] = new SqlParameter("@ProductStock", SqlDbType.BigInt);
        param[10] = new SqlParameter("@ProductSWarning", SqlDbType.BigInt);
        param[11] = new SqlParameter("@ProductWarehouse", SqlDbType.NVarChar, 255);
        param[12] = new SqlParameter("@ProductPNotes", SqlDbType.Text);

        param[13] = new SqlParameter("@ProductImage", SqlDbType.VarBinary, bytBLOBData.Length, ParameterDirection.Input, false,
        0, 0, null, DataRowVersion.Current, bytBLOBData);

        int unit; int cost; int pc; int stock; int war;
        param[0].Value = txtCode.Text;
        param[1].Value = ComboStatus.Text;
        param[2].Value = ComboCategory.Text;
        param[3].Value = txtName.Text;
        param[4].Value = txtDescription.Text;
        param[5].Value = Int32.TryParse(txtUnit.Text, out unit);
        param[6].Value = Int32.TryParse(txtCost.Text, out cost);
        param[7].Value = Int32.TryParse(txtPC.Text, out pc);
        param[8].Value = txtWeight.Text;
        param[9].Value = Int32.TryParse(txtStock.Text, out stock);
        param[10].Value = Int32.TryParse(txtWarhouse.Text, out war);
        param[11].Value = txtWarhouse.Text;
        param[12].Value = txtNotes.Text;

        for (int j = 0; j < param.Length; j++)
        {
            cmd.Parameters.Add(param[j]);
        }

        cmd.CommandType = CommandType.Text;
        cmd.ExecuteNonQuery();

        bmsmf1.loadProductServicesTable();
        this.Hide();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        conn.Close();
    }
}

【问题讨论】:

  • Int32.TryParse 返回一个布尔值,因此结果是可以预期的。如果您想保存解析结果,请查看您未使用的时髦 out 参数。然后阅读How to Ask 并采取tour
  • 你应该阅读关于TryParse的文档
  • 我认为他/她对 out 参数的使用比其他任何事情都感到困惑。

标签: c# winforms visual-studio int tryparse


【解决方案1】:

你得到一个布尔值的原因是你传递了一个布尔值。 int.TryParse(string s, out x) 将返回 True 或 False。如果要访问解析后的 int 值,则需要使用在 out 部分中分配的 x 变量。

【讨论】:

  • 你能给我一个演示代码吗?这对我有很大帮助。请。
  • @user8441838 你不需要演示代码,你需要阅读文档
  • @user8441838 我的答案几乎是演示代码。我同意@maccettura 的观点,熟悉TryParse 的作用会更好。
  • 我阅读了文档并且它有效,但仅适用于一个值。剩余的 TryParse 仍在传递布尔值。
  • @user8441838 TryParse 总是会返回一个布尔值。这就是它的作用。如果它停止这样做,请告诉我,因为我有很多代码会变得非常糟糕。您需要使用分配给 out 参数的值。 TryParse 允许您尝试将字符串解析为整数。它会告诉你这是成功还是失败。然后,为了节省您的时间,如果可以的话,继续为您解析该字符串就足够了。因此,如果 TryParse 返回 True,请随意使用解析后的值,现在保存在您的 out 参数中。
【解决方案2】:

问题是您将字段的值设置为返回布尔值的int.TryParse() 方法的返回结果。

只需将值设置为out中的返回值即可。

Int32.TryParse(txtUnit.Text, out unit);
param[5].Value = unit;

【讨论】:

  • 它有效,但仅适用于一个值。剩余的 TryParse 仍在传递布尔值。
【解决方案3】:

快速回答:您的代码已设置为使用 int.Parse(string) 替换它会使其正常工作。

int.TryParse(string, out int) 是一个函数,用于确保当字符串不能被 Int32 表示时,它不会返回默认值(因为 int 不是可空类型)。如果 TryParse 返回 true,则字符串已成功转换为 int。

TryParse 示例:

int num;
if (int.TryParse("1", out num))
{
    Console.WriteLine(num);
}

解析示例:

int num = int.Parse("1");

【讨论】:

  • 我试过了,但在 int.Parse 上出现“输入字符串格式不正确”的异常。
【解决方案4】:

请看这个例子:

public class Example
{
   public static void Main()
   {
      String[] values = { null, "160519", "9432.0", "16,667",
                          "   -322   ", "+4302", "(100);", "01FA" };
      foreach (var value in values) {
         int number;

         bool result = Int32.TryParse(value, out number);
         if (result)
         {
            Console.WriteLine("Converted '{0}' to {1}.", value, number);         
         }
         else
         {
            Console.WriteLine("Attempted conversion of '{0}' failed.", 
                               value == null ? "<null>" : value);
         }
      }
   }
}

输出

//       Attempted conversion of '<null>' failed.
//       Converted '160519' to 160519.
//       Attempted conversion of '9432.0' failed.
//       Attempted conversion of '16,667' failed.
//       Converted '   -322   ' to -322.
//       Converted '+4302' to 4302.
//       Attempted conversion of '(100);' failed.
//       Attempted conversion of '01FA' failed.

如果转换正确完成,则返回true,否则返回false。所以这个例子中的result变量是true(1)或者false(0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-24
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 2015-12-26
    • 2015-08-03
    • 2021-06-08
    相关资源
    最近更新 更多