Search code examples
c#arrayssql-serverstored-proceduressqlparameter

How can I add members to an array of SqlParameter?


I've got this code:

private SqlParameter[] GetSPParams()
{
    SqlParameter[] spParams = null;
    int loopNum = 1;
    while (ParamExists(loopNum))
    {
        //spParams.
        new SqlParameter()
        {
            ParameterName = GetParamName(loopNum),
            SqlDbType = GetSqlDbType(loopNum),
            Value = GetParamValue(loopNum)
        };
        loopNum++;
    }
    return spParams;
}

...which, as you can see, returns null always.

The "spParams." is commented out because I found no "Add" or such among the Intellisense possibilities - or anything that looked right.

I need a SqlParameter array, because that is what ends up getting passed to my method that runs the Stored Proc:

private void RunStoredProc()
{
    SqlParameter[] spparams = GetSPParams();
    DataTable dtSPResults = SPRunnerSQL.ExecuteSQLReturnDataTable(comboBoxCPSStoredProcs.Text,
        CommandType.StoredProcedure,
        spparams
    );
    rowsReturned = dtSPResults.Rows.Count;
    labelRowsReturned.Text = String.Format("Rows returned: {0}", rowsReturned);
    if (rowsReturned > 0)
    {
        dataGridView.DataSource = dtSPResults;
    }
}

. . .

public static DataTable ExecuteSQLReturnDataTable(string sql, CommandType cmdType, params SqlParameter[] parameters)

So how can I add SqlParameter values to the SqlParameter array?


Solution

  • You could use a List<SqlParameter> instead a array, then you should be able to add new elements. Then, just return an array calling the method ToArray() to convert the collection into an array.

    private SqlParameter[] GetSPParams()
    {
        var spParams = new List<SqlParameter>();
        int loopNum = 1;
        while (ParamExists(loopNum))
        {
            spParams.Add(new SqlParameter()
            {
                ParameterName = GetParamName(loopNum),
                SqlDbType = GetSqlDbType(loopNum),
                Value = GetParamValue(loopNum)
            });
        }
        return spParams.ToArray();
    }
    

    Now, if you need to add nem members, you could derive from SqlParameter but as the documentation, this class is sealed.