Marius Vasile

Marius Vasile

  • 590
  • 1.9k
  • 146.1k

Passing array as parameter for sql query

Oct 29 2023 9:55 AM

I couldn't find an answer for this questions no matter how much I tried. What I have so far is this:

The array of data is gathered and displayed with

readonly string[] values;
protected void btnAddClick(object sender, EventArgs e)
{
    List<string> values = new List<string>
    {
        txtActivitate.Text.ToString()
    };

    for (int i = 0; i < values.Count; i++)
    {

        Message.Text += values[i] + "<br />";

    }
}

and is working properly. Then I try a select with

protected void btnSelectClick(object sender, EventArgs e)
{
    foreach (string val in values)
    {
        using (SqlConnection conn = new SqlConnection(connString))
        {
            string sqlQuery = "SELECT * FROM tblActivitate t1 JOIN tblEvaris t2 ON t1.AID = t2.AID JOIN tblMasura t3 on t2.EID = t3.EID WHERE t1.Activitate = @Activitate ORDER BY Componenta, FactorRisc, FormaManifestare";
            using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
            {
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@Activitate", val);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                conn.Open();
                DataSet ds = new DataSet();
                da.Fill(ds);
                DataList1.DataSource = ds.Tables[0];
                DataList1.DataBind();
                conn.Close();
            }
        }
    }
}

and I got error

System.NullReferenceException: 'Object reference not set to an instance of an object.' Local0 was null.
How it should be done?


Answers (11)