0

Hello I'm having an issue passing the value to SP parameter, inline query is working fine. My task is to select multiple items from the dorpdownlist and display it in a gridview. I have two dropdown when I select the value from first dropdown then second dropdown is filled on the basis of the first dropdown from db on button click.

Here is what I have done so far,

     protected void btnGetResult_Click(object sender, EventArgs e)
    {
        string selectedListValue = hdnSelections.Value;
        if (!string.IsNullOrEmpty(selectedListValue))
        {
            string[] finalList = selectedListValue.TrimEnd(',').Split(',');

            var parameters = new string[finalList.Length];
            var cmd = new SqlCommand();
            for (int i = 0; i < finalList.Length; i++)
            {
                if (!string.IsNullOrEmpty(finalList[i]))
                {
                    parameters[i] = string.Format("@cardcode{0}", i);
                    cmd.Parameters.AddWithValue(parameters[i],finalList[i]);
                }
            }

           cmd.CommandText = string.Format("Select cardcode, FirstName from 
          nonSAPcustomer where cardcode IN ({0})", string.Join(", ", 
            parameters));
          // cmd.CommandText= string.Format("sp_nonSAPcustomer", 
            parameters);
            cmd.Connection = Connection.con;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            lstBoxcities.DataSource = dt;
            lstBoxcities.DataValueField = "cardcode";
            lstBoxcities.DataTextField = "FirstName";
            lstBoxcities.DataBind();
        }

    }      

enter image description here

L Y E S - C H I O U K H
  • 4,765
  • 8
  • 40
  • 57
Oliver james
  • 162
  • 11

1 Answers1

0

You can use Table-Valued parameters.

First, create a Type:

CREATE TYPE CardCodes AS TABLE ( CardCode INT);  

Then, add a parameter of that type

CREATE PROCEDURE dbo.YourProc
    @Codes CardCodes READONLY 
AS
BEGIN
     SELECT *
     FROM FOO
     WHERE ID IN(SELECT Code From @Codes)
END

And then send the values using, though I think there are other recipes, I use DataTables:

var dataTable = new DataTable();
dataTable.Columns.Add("CardCode", typeof(int));

PopulateTable(dataTable);

cmd.Parameters.Add("@Codes", dataTable);
hardkoded
  • 18,915
  • 3
  • 52
  • 64