将函数作为参数传递到SQL Server中

时间:2016-10-16 13:12:35

标签: c# sql-server

我写了一个GetLoan函数:

private void GetLoan(RadioButton radiobutton)
{
        if(radiobutton.Checked)
        {
            MessageBox.Show(radiobutton.Text);
        }
}

为了从单选按钮获取必要的数据,我做了这个,

bookCom = new SqlCommand("UPDATE d_Book SET ISBN = @isbn, Author = @author, Title = @title, Publisher = @publisher, Date = @date, Loan = @loan WHERE ISBN = @isbn ", bookCon);

String ISBN = textISBN.Text;
String Author = textAuthor.Text;
String Title = textTitle.Text;
String Publisher = textPublisher.Text;
String Date = textDate.Text;

GetLoan(rdbtn_Yes); // worked fine
GetLoan(rdbtn_No);  // worked fine

bookCom.Connection = bookCon;
bookCon.Open();

if (bookCon.State == ConnectionState.Open)
{
    bookCom.Parameters.AddWithValue("@isbn", ISBN);
    bookCom.Parameters.AddWithValue("@author", Author);
    bookCom.Parameters.AddWithValue("@title", Title);
    bookCom.Parameters.AddWithValue("@publisher", Publisher);
    bookCom.Parameters.AddWithValue("@date", Date);
    bookCom.Parameters.Add("@loan", SqlDbType.Char).Value = GetLoan; // didn't work at all
}

我有什么方法可以让GetLoan工作吗?

2 个答案:

答案 0 :(得分:0)

您必须在函数中指定返回类型:

new

或者作为一行代码中的bool:

    private string GetLoan(RadioButton radiobutton)
    {
        if (radiobutton.Checked)
        {
            return "yes";
        }
        else
        {
            return "no";
        }
    }

然后你总是需要传递 private bool GetLoan(RadioButton radiobutton) { return radiobutton.Checked; } 作为参数。所以改变

RadioButton

bookCom.Parameters.Add("@loan", SqlDbType.Char).Value = GetLoan;

但为什么不让它变得更容易,只需检查选择哪一个:

bookCom.Parameters.Add("@loan", SqlDbType.Char).Value = GetLoan(rdbtn_Yes);

答案 1 :(得分:0)

通过阅读提供的代码段,我了解您需要询问用户他/她是否对贷款感兴趣。 您可以考虑使用复选框,然后使用以下功能,而不是是或否的单选按钮。

private string GetLoan(CheckBox chkBxGetLoan)
{
    //returns string value as output.
    return chkBxGetLoan.Checked ? "Y" : "N";
}

OR

private char GetLoan(CheckBox chkBxGetLoan)
{
    //returns char value as output.
    return chkBxGetLoan.Checked ? 'Y' : 'N';
}