填充列表框,其中包含存储过程C#的结果

时间:2015-03-24 18:01:50

标签: c# sql-server wpf stored-procedures

我为此搜索了一堆,因为你可以说我对C#很新,我正在努力学习这门语言。

所以请原谅我,如果我看过的100个表格中的一个说你在这里发布的内容相同。

我正在尝试使用名为LookupInvoices的存储过程的结果填充列表框,这需要一个@InvoiceNumber的参数int

我有一个WPF,我希望使用此存储过程的结果填充名为lstResults的列表框。

请查看我的代码并告诉我我在哪里犯了错误,非常感谢您的时间!

private void btnFill_Click(object sender, RoutedEventArgs e)
{
    if (cmbInvoiceNumbers.SelectedItem == null)
    {
        System.Windows.MessageBox.Show("Please Choose A Invoice Number!");
        return;
    }

    SqlConnection cs = new SqlConnection("Data Source=JAMES-DESKTOP\\SQLEXPRESS;Initial Catalog=contacts;Integrated Security=True");

    int cboItemNumber = cmbInvoiceNumbers.SelectedIndex;
    int invNumber = Convert.ToInt32(cmbInvoiceNumbers.Items[cboItemNumber].ToString());

    cs.Open();

    SqlCommand cmd = new SqlCommand("LookupInvoices", cs);

    using (SqlDataReader reader = cmd.ExecuteReader())
    {
        SqlParameter pram = new SqlParameter("@invoiceNumber", invNumber);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add(pram);
        cmd.Connection = cs;

        reader.Read();
    }

    cs.Close();
}

请注意,当我点击按钮时它会崩溃。这不会一直运行。

1 个答案:

答案 0 :(得分:2)

您应该将所有可支配元素(SqlConnectionSqlCommandSqlDataReader)放入using (....) { ...... }块中,并且需要添加参数 调用.ExecuteReader()之前 - 尝试以下代码:

public class InvoiceDto
{
    public string Description { get; set; }
    public int Hours { get; set; }
    public decimal Amount { get; set; }
}

public void List<InvoiceDto> GetInvoiceData(int invoiceNumber)
{
    List<InvoiceDto> data = new List<InvoiceData>();

    using (SqlConnection cs = new SqlConnection("Data Source=JAMES-DESKTOP\\SQLEXPRESS;Initial Catalog=contacts;Integrated Security=True"))
    using (SqlCommand cmd = new SqlCommand("dbo.LookupInvoices", cs))
    {
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.Add("@invoiceNumber", SqlDbType.Int).Value = invoiceNumber;

        cs.Open();

        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                InvoiceDto dto = new InvoiceDto();
                dto.Description = reader.GetFieldValue<string>(0);
                dto.Hours = reader.GetFieldValue<int>(1);
                dto.Amount = reader.GetFieldValue<decimal>(2);

                data.Add(dto);
            }
        }

        cs.Close();
    }

    return data;
}

在您的代码隐藏中,您应该在事件处理程序中调用此方法

private void btnFill_Click(object sender, RoutedEventArgs e)
{
     // get selected invoice number
     int cboItemNumber = cmbInvoiceNumbers.SelectedIndex;
     int invNumber = Convert.ToInt32(cmbInvoiceNumbers.Items[cboItemNumber].ToString());

     // call method to get the data from the stored procedure
     List<InvoiceDto> data = GetInvoiceData(invNumber);

     // loop over the data and fill your listbox
     foreach(InvoiceDto dto in data)
     {
         listbox.Items.Add(dto.Description);
     }
}