如何将按钮单击链接到数据源以运行存储过程

时间:2017-05-27 23:06:08

标签: c# sql sql-server

我已经想出了如何创建下拉框,将它们链接到各自的数据源,以及创建链接到存储过程的数据源。我无法弄清楚如何将按钮链接到数据源以在单击时运行存储过程。我正和VS 2017合作。

HTML标记:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ChangeShiftStat.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    &nbsp; Shift&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="ShiftDataSource" DataTextField="Shift" DataValueField="Shift">
        </asp:DropDownList>
        <br />
        <br />
&nbsp; New Status&nbsp;&nbsp;&nbsp;
        <asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" DataSourceID="StatusDataSource" DataTextField="Status" DataValueField="Status">
        </asp:DropDownList>
        <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="Button1" runat="server" Text="Change Status" />
        <asp:SqlDataSource ID="ShiftDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:TheBoardConnectionString %>" SelectCommand="SELECT * FROM [Shifts]"></asp:SqlDataSource>
        <asp:SqlDataSource ID="StatusDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:TheBoardConnectionString %>" SelectCommand="SELECT * FROM [Statuses]"></asp:SqlDataSource>
        <asp:SqlDataSource ID="RunSP" runat="server" ConnectionString="<%$ ConnectionStrings:TheBoardConnectionString %>" SelectCommand="changeshiftstat" SelectCommandType="StoredProcedure">
            <SelectParameters>
                <asp:ControlParameter ControlID="DropDownList1" Name="Shift" PropertyName="SelectedValue" Type="String" />
                <asp:ControlParameter ControlID="DropDownList2" Name="NewStat" PropertyName="SelectedValue" Type="String" />
            </SelectParameters>
        </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

C#代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}

1 个答案:

答案 0 :(得分:0)

您需要通过按钮的点击事件提交sql command。将CommandText设置为存储过程的名称,将commandType设置为commandType.StoredProcedure。根据您的要求,您可以按照this打开阅读器,也可以按照this教程执行非查询命令。