关闭

处理带参数的存储过程

373人阅读 评论(0) 收藏 举报

存储过程:
CREATE PROCEDURE Customer_Select
    @country nvarchar(15)
 AS
select CustomerID,CompanyName,ContactName from Customers where Country=@country
go

.aspx: 
<form id="form1" runat="server">
    <div>
        &nbsp;<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True">
            <asp:ListItem Value="USA">USA</asp:ListItem>
            <asp:ListItem Value="UK">UK</asp:ListItem>
            <asp:ListItem Value="France">France</asp:ListItem>
            <asp:ListItem Value="Canada">Canada</asp:ListItem>
            <asp:ListItem Value="Norway">Norway</asp:ListItem>
        </asp:DropDownList><br />
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
        &nbsp;</div>
    </form>

.cs:
 protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        //创建连接字符串
        string ConnString = "Data Source=.;Initial Catalog=Northwind;User ID=sa;Password=sa";

        //创建操作对象
        SqlDataAdapter adp = new SqlDataAdapter();

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = new SqlConnection( ConnString);
        DataTable dt = new DataTable();

        //制定要调用的存储过程名称"Customer_Select";
        //指定sqlcommand对象的命令类型为StoredProcedure 枚举类型
        cmd.CommandText = "Customer_Select";
        cmd.CommandType = CommandType.StoredProcedure;
        //指定 SqlParameter对象,指定参数名称,数据类型 长度以及参数
        SqlParameter para = new SqlParameter("@country",SqlDbType.NVarChar,15);
        para.Value = DropDownList1.SelectedValue;
        cmd.Parameters.Add(para);
        //关联SqlDataAdapter和sqlcommand
        adp.SelectCommand = cmd;
        adp.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();

    }

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:31098次
    • 积分:397
    • 等级:
    • 排名:千里之外
    • 原创:11篇
    • 转载:9篇
    • 译文:0篇
    • 评论:3条
    文章分类
    最新评论