基于组合框选择的SQL查询

时间:2017-03-19 18:07:21

标签: c# sql winforms

我正在创建一个数据库应用程序,但我在实现查询时遇到了困难。我有一个查询,它使用客户的银行帐户填充组合框,这是查询的代码:

private void ShowAccounts()
            {
                string sql = "SELECT account.custid, product.name FROM account INNER JOIN product ON account.prodid = product.prodid WHERE account.custid = @AccountID";
                using (OleDbConnection connection = new OleDbConnection(Properties.Settings.Default.ConnectionScring))
                {
                    OleDbCommand command = new OleDbCommand(sql, connection);
                    command.Parameters.AddWithValue("@AccountID", customerData.CustomerID);
                    connection.Open();

                    using (OleDbDataReader reader = command.ExecuteReader())
                    {

                        while (reader.Read())
                        {
                            comboAccounts.Items.Add(reader["name"].ToString());
                        }


                    }
                }

这是我需要它的方式,但根据我需要显示帐户余额的帐户选择,我想知道如何编写该查询。任何帮助将不胜感激。

谢谢

1 个答案:

答案 0 :(得分:0)

我想这就是你要做的事情?我猜你的列名和表名,所以如果我弄错了你需要修改sql语句。

    private string Get_Balance(string AccountNumber)
    {
        string sql = "SELECT balance FROM account WHERE custid = @AccountID";
        string balance = "";
        using (OleDbConnection connection = new OleDbConnection(Properties.Settings.Default.ConnectionScring))
        {
            OleDbCommand command = new OleDbCommand(sql, connection);
            command.Parameters.AddWithValue("@AccountID", AccountNumber);
            connection.Open();

            using (OleDbDataReader reader = command.ExecuteReader())
            {

                while (reader.Read())
                {
                    balance = reader["balance"].ToString();
                }
            }
        }
        return (balance);
    }

使用组合框的SelectedIndexChanged事件来调用上面的代码。您需要将事件处理程序添加到组合框中(只需在表单上双击它,VS就会为您执行此操作)。

    private void comboAccounts_SelectedIndexChanged(object sender, EventArgs e)
    {
        if(comboAccounts.Text != "")
        {
            balanceLabel.text = Get_Balance(comboAccounts.text); //Or whatever you named the label you want your balance to to into.
        }
    }

使用代码填充组合框后,每当组合框被删除并更改时,它会将组合框中任何内容的文本传递给Get_Balance,这将返回将放置在标签中的字符串。 / p>