【问题标题】:How do I get this to display the numerical? [duplicate]我如何让它显示数字? [复制]
【发布时间】:2021-09-15 12:07:58
【问题描述】:

我正在尝试为租车服务创建一个计算器。本质上,我必须能够将用户输入的开始日期和结束日期与存储在数据库中的值相乘以获取价格。我在 Visual Studio 中编写代码,数据库在 Microsoft SQL Server 中完成。以下是我尝试过的代码,但它一直在为数据库返回字符串命令中的字母。谁能告诉我如何才能让它返回实际金额?

private void button8_Click(object sender, EventArgs e)
    {
        DateTime startdate = dateTimePicker1.Value.Date;
        DateTime enddate = dateTimePicker2.Value.Date;

        int no_of_days = ((TimeSpan)(enddate - startdate)).Days;
        int no_of_weeks = no_of_days/7;
        int no_of_months = no_of_weeks / 4;
        

        string query_week = " Select weekly_rent from Rent *no_of_weeks";
        string query_month = " Select monthly_rent from Rent *no_of_months";
        string query_days = " Select daily_rent from Rent *no_of_weeks";

        SqlCommand cmd = new SqlCommand(query_week, con);
        SqlCommand cmd1 = new SqlCommand(query_month, con);
        SqlCommand cmd2 = new SqlCommand(query_days, con);

        string total = query_week + query_month + query_days;

        label12.Text =  total.ToString();

【问题讨论】:

  • total 变量只是连接您创建的三个字符串。您实际上并没有执行任何查询。
  • 不完全是,但我确实找到了另一种方法,谢谢。

标签: c#


【解决方案1】:

这是您可能需要创建的从数据库读取数据的方法。

    // your method to get Rent data from database 
    public static DataTable GetRentData(string sqlQueryCommand)
    {
        DataTable dataTable = new DataTable();
        string connString = @"Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";
        //refer https://www.connectionstrings.com/sql-server/  for setting differnt type of connection string.
        // the connection string can be initiliase in your configurations classes. I left it here so that you can test your feature.
        
        using (SqlConnection connection = new SqlConnection(connString))
        {
            SqlCommand cmd = new SqlCommand(sqlQueryCommand, connection);
            connection.Open();
            // create data adapter
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            // this will query your database and return the result to your datatable
            da.Fill(dataTable);
            connection.Close();
            da.Dispose();           
        }
        return dataTable;
    }

然后,您可以在 button8_Click 方法中调用上述方法来计算租金:

    int no_of_days = ((TimeSpan)(enddate - startdate)).Days;
    int no_of_weeks = no_of_days/7;
    int no_of_months = no_of_weeks / 4;
    
    var data = GetRentData("Select weekly_rent,monthly_rent ,daily_rent  from Rent");
    long total = Convert.ToInt32(data.Rows[0]["monthly_rent"])*no_of_months + 
        Convert.ToInt32(data.Rows[0]["weekly_rent"]) * no_of_weeks+
        Convert.ToInt32(data.Rows[0]["daily_rent"]) * no_of_days;
    
    label12.Text =  total.ToString();

【讨论】:

  • 是的,谢谢,我想我会做一些类似的事情,但我是在同一个按钮点击事件中完成的。
猜你喜欢
  • 2020-10-09
  • 2023-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多