1

I am trying to call a SQL Server stored procedure that returns multiple values for instance say if you enter id = 1, it returns the name of all the people with id = 1.

Now, my goal is to store the id's in a list of type string. I tried the following but for some reason, the list always returns null and I cant find out why the results are not stored in the list.

Kindly help me figure out my mistake. This is what I tried so far. I get error in the following lines and I am unable to understand why I keep error.

fname = rdr["Fullname"].ToString;
names.add(fname);

SQL Server code:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[login_users]
    (@uname NVARCHAR(50), @pass NVARCHAR(50))
AS
BEGIN
    SET NOCOUNT ON;

    SELECT UserName, Password, Fullname
    FROM dbo.users
    WHERE UserName = @uname AND [Password] = @pass
END

C# code:

protected void LogIn_Click(object sender, EventArgs e)
{
    establishconnection();

    String username = usernamelogin.Text;
    String password = passwordlogin.Text;

    String fname = null;

    List<String> names;

    establishconnection();

    try
    {
        cnn.Open();

        SqlCommand cmd = new SqlCommand("dbo.login_users", cnn);
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.Add(new SqlParameter("@uname", username));
        cmd.Parameters.Add(new SqlParameter("@pass", password));

        using (SqlDataReader rdr = cmd.ExecuteReader())
        {
            // iterate through results, printing each to console
            while (rdr.Read())
            {
                fname = rdr["Fullname"].ToString;
                names.add(fname);
            }
        }

        cnn.Close();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

1

You need to instantiate the list before you can add new items.

....
List<string> names = new List<string>();
.....
Marko Juvančič
  • 5,792
  • 1
  • 25
  • 41