我希望使用文本框选择列表视图和列计算

时间:2016-06-25 10:18:14

标签: c# sql-server

SqlCommand cm = new SqlCommand(@"Select StockID,FoodId,StockName,StockDate,
                               StockNum,UnID,StockMin,StockCalulate 
                               from StockCalutale", Conn);
try
{
    int currency = int.Parse(txtAmount.Text);
    SqlDataReader dr = cm.ExecuteReader();
    while (dr.Read())
    {
        ListViewItem item = new ListViewItem(dr["StockID"].ToString());
        item.SubItems.Add(dr["FoodId"].ToString());
        item.SubItems.Add(dr["StockName"].ToString());
        item.SubItems.Add(dr["StockDate"].ToString());
        item.SubItems.Add(dr["StockNum"].ToString());
        item.SubItems.Add(dr["UnID"].ToString());
        item.SubItems.Add(dr["StockMin"].ToString());
        item.SubItems.Add(dr["StockCalulate"].ToString()* txtAmount.Text);

        listView1.Items.Add(item);
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "EROR");
}

1 个答案:

答案 0 :(得分:1)

这里

item.SubItems.Add(dr["StockCalulate"].ToString()* txtAmount.Text);

您不能将字符串与另一个字符串相乘。如果两个字符串包含数字,那么它们也没有意义。 C#没有像VB.NET这样的自动转换(幸运的是)你需要将两个字符串转换为数字然后进行乘法运算。一个已经转换,虽然是异常就绪方式。

SqlCommand cm = new SqlCommand(@"Select StockID,FoodId,StockName,StockDate,
                               StockNum,UnID,StockMin,StockCalulate 
                               from StockCalutale", Conn);
try
{
    int currency = 0;

    // When input comes from the user don't trust its ability with the keyboard
    // use a foolproof way to check its input....
    if(!Int32.TryParse(txtAmount.Text, out currency))
    {
        MessageBox.Show("Invalid currency value!");
        return;
    }

    SqlDataReader dr = cm.ExecuteReader();
    while (dr.Read())
    {
        // Also this line is risky. I assume that you never have null values
        // in this StockCalulate field otherwise you need to check with dr.IsDbNull
        int value = Convert.ToInt32(dr["StockCalulate"].ToString());
        int newStock = value * currency;

        ListViewItem item = new ListViewItem(dr["StockID"].ToString());
        item.SubItems.Add(dr["FoodId"].ToString());
        item.SubItems.Add(dr["StockName"].ToString());
        item.SubItems.Add(dr["StockDate"].ToString());
        item.SubItems.Add(dr["StockNum"].ToString());
        item.SubItems.Add(dr["UnID"].ToString());
        item.SubItems.Add(dr["StockMin"].ToString());

        item.SubItems.Add(newStock.ToString());
        listView1.Items.Add(item);
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "EROR");
}

顺便说一句,我不确定这里使用的数据类型,如果你需要保留小数,那么考虑使用十进制数据类型和等效的转换方法(decimal.TryParse和Convert.ToDecimal)。