简体   繁体   中英

How to pass the parameter of a stored procedure on page load

How to pass the parameter of a stored procedure on page load? It needs to be an overload.

protected void bind(DateTime dt)
{
    SqlConnection cn = new SqlConnection(conString);
    SqlCommand cmd = new SqlCommand();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "HeadCount03";
    cmd.Parameters.AddWithValue("@years", ddlyear.SelectedValue);
    cmd.Parameters.AddWithValue("@months", ddlMonths.SelectedValue);
    cmd.Parameters.AddWithValue("@Cal", Convert.ToInt32(dt));
    cmd.Connection = cn;
    try
    {
        cn.Open();
        GridView2.EmptyDataText = "No Records Found";
        GridView2.DataSource = cmd.ExecuteReader();
        GridView2.DataBind();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        cn.Close();
        cn.Dispose();
    }
    if (!IsPostBack)
    {
        bind();
    }
}

protected void btnGenerate_Click(object sender, EventArgs e)
{    
    DateTime Cal = new DateTime(
        Convert.ToInt32(ddlyear.SelectedValue),
        Convert.ToInt32(ddlMonths.SelectedValue),
        1);

    bind(Cal);
}

Im trying to figure out what you ment by this question, the way I see it you are gonna need a Form_load event.

private void Form_Load(object sender, EventArgs e)
{
    bind(DateTime.Now());
}

Althought you should really add some more information. For instance, what does this line mean?

cmd.CommandText = "HeadCount03";

EDIT

Adding parameters on an event can be done like so:

private void Form_Load(object sender, EventArgs e, string parameter)
{
    //whatever
}

Call it like this using lambda expressions:

(sender, e) => Form_Load(sender, e, parameter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM