首页 > 解决方案 > 我需要在我的代码中添加 int 变量,有什么想法吗?

问题描述

private void button1_Click(object sender, EventArgs e)
{
    cmd = new SqlCommand("select * from package where pkgid = '" + txtpkgid.Text + "' ", con);
    con.Open();
    dr = cmd.ExecuteReader();

    while (dr.Read())
    {
        int HC = Convert.ToInt32(dr["HC"]);
        int KC = Convert.ToInt32(dr["KC"]);
        int DC = Convert.ToInt32(dr["DC"]);
        int DONR = Convert.ToInt32(dr["DONR"]);
        int VNPR = Convert.ToInt32(dr["VNPR"]);

    }
    con.Close();


    cmd = new SqlCommand("select * from vehicle where RegistrationNo = '" + txtcarid.Text + "' ", con);
    con.Open();
    dr = cmd.ExecuteReader();

    while (dr.Read())
    {
        int VDP = Convert.ToInt32(dr["VDP"]);
    }
    con.Close();
}

如何添加以上内容?

抱歉,我是初学者,所以这可能看起来很愚蠢,非常感谢任何有关如何将它们添加在一起的帮助。

基本上我想得到 Result = HC+KC+DC+DONR+VNPR+VDP 并在标签中显示结果。

问题是我不知道如何将 VDP 的价值带出来。

标签: c#winforms

解决方案


这些方面的东西:

    long result = 0;
    while (dr.Read())
    {
        result += Convert.ToInt32(dr["HC"]);
        result += Convert.ToInt32(dr["KC"]);
        result += Convert.ToInt32(dr["DC"]);
        result += Convert.ToInt32(dr["DONR"]);
        result += Convert.ToInt32(dr["VNPR"]);

    }
    con.Close();

请注意,您应该正确处理命令和读取器对象。正如其他评论者指出的那样,您可以在 SQL 端计算此总和,因此您不必遍历结果集。如果您继续使用客户端迭代器,还记得添加适当的 NULL 处理,以防 dr[...] 可以返回 a nullor DBNull.Value


推荐阅读