如何将asp.net下拉列表选项作为输入传递给c#中的存储过程?

时间:2012-08-28 09:05:57

标签: c# stored-procedures drop-down-menu selecteditem

这是我正在使用的代码..我想将下拉列表选中的项目作为输入传递给存储过程并执行..我怎么能实现呢?

public class DaysForEvents
{
    public DataSet GetDaysForEvents(//This should be my input to stored procedure (i.e)  dropdownselected value)
    {
        SqlConnection con = new SqlConnection(CommonSettings.GetEventsConnectionString());

        try
        {
            SqlCommand sqlcmd = new SqlCommand("proc_fetch_event_days", con);
            SqlDataAdapter sqlda = new SqlDataAdapter(sqlcmd);
            DataSet ds = new DataSet();
           //DateFilter = 0;
            //StatusFilter = 0;

            sqlcmd.CommandType = CommandType.StoredProcedure;

            sqlcmd.Parameters.AddWithValue("@event_id", Event_id);
            // sqlcmd.Parameters["@UserID"].Value = UserID;


            con.Open();
            sqlda.Fill(ds);
            con.Close();

            return ds;


        }

4 个答案:

答案 0 :(得分:1)

据我了解,你想要这个。

//get dropdown selected value and store in a variable 
var eventId = dropdown.SelectedValue; 

//pass this variable in the GetDaysForEvents method to get DataSet.
var dataSet = GetDaysForEvents(eventId); 

答案 1 :(得分:0)

sqlcmd.Parameters.AddWithValue("@event_id", yourDropDown.SelectedValue);

答案 2 :(得分:0)

将您的功能称为

string eventId = ddlEvents.SelectedValue;
GetDaysForEvents(eventId);

答案 3 :(得分:0)

-User using语句,用于关闭连接并处置未使用的资源。

- DataAdapter自行打开连接,因此无需Open();

public DataSet GetDaysForEvents(string eventId)
{
    var ds = new DataSet();
    using(var connection = new SqlConnection("ConnectionString"))
    {
        using(var cmd = new SqlCommand("storedProcedureName", connection){ CommandType = CommandType.StoredProcedure })
        {
            cmd.Parameters.AddWithValue("@EventId", eventId);
            using(var adapter = new SqlDataAdapter(cmd))
            {
                adapter.Fill(ds);
            }
        }
    }
    return ds;
}

以及其他地方

var events = yourClassInstance.GetDaysForEvents(dropDown.SelectedValue);