简体   繁体   中英

C# ListView is not displaying database results using stored procedure and parameter

My listview is not displaying the results when the stored procedure is ran with a parameter. The listview should show the transactions for the selected account.

The code I use works perfectly when ran with a different stored procedure and no parameters. I checked the stored procedure on the database and it works the way it should, displaying the transactions for the selected account.

            transactionListView.Items.Clear();
            SqlConnection sql = new SqlConnection(@"Server=.\DANIELSQL;Database=Accounts;Trusted_Connection=True;");
            sql.Open();

            SqlCommand com = new SqlCommand("spTransactionTable_GetTransactionDetails_ByAccount", sql);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@AccountName", accountNameChoice.SelectedItem.ToString());

            SqlDataAdapter da = new SqlDataAdapter(com);
            DataTable dt = new DataTable();
            da.Fill(dt);

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];

                if (dr.RowState != DataRowState.Deleted)
                {
                    ListViewItem lvi = new ListViewItem(dr["TransactionID"].ToString());
                    lvi.SubItems.Add(dr["AccountName"].ToString());
                    lvi.SubItems.Add(dr["TransactionAmount"].ToString());
                    lvi.SubItems.Add(dr["Category"].ToString());
                    lvi.SubItems.Add(dr["DateValue"].ToString());
                    lvi.SubItems.Add(dr["IncomeOrExpenditure"].ToString());

                    transactionListView.Items.Add(lvi);
                }
            }

            sql.Close();

When I run the no parameter stored procedure all the records are shown. When I run the parameterised stored procedure nothing is shown.

I tired placing a breakpoint starting on SqlDataAdapter on both stored procedures. When it gets to the for loop, on the non parameterised stored procedure it says that it is filled with 3, which is how many transactions there are. On the parameterised stored procedure it says that it is filled with 0.

尝试使用SSMS中的输入执行存储过程,并检查它是否返回任何结果。

If accountNameChoice.SelectedItem.ToString() is displaying the name of the class, you need to work out what the class is, and which property of that class represents the account name.

An example of what this might look like when you pass the value to the stored procedure:

((Account)accountNameChoice.SelectedItem).Name

This would be the case if you had a class such as:

public class Account
{
    public string Name { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM