【问题标题】:Calling SQL Procedure from C# / ASp.NET从 C# / ASp.NET 调用 SQL 过程
【发布时间】:2017-09-07 13:10:30
【问题描述】:

我一直在为雇主开发一个包含数据库信息的网站,允许用户随意编辑信息。我收到的一个请求是添加一个名为 Deactivate 的按钮,单击该按钮应将标签“X”添加到名为“Inactive”的列中,说明该行实际上对任何选中了复选框的行都是无效的。复选框已添加到 GridView。

我尝试通过 SQL Server Management Studio 添加存储过程,但是按照 Microsoft 文档中列出的教程,当我右键单击存储过程文件夹时,我没有添加/创建新存储过程的选项。

我已经在互联网上搜索了几天,我不知道我是否没有找到正确的答案,或者我只是没有正确理解它们。

SQL 停用命令伪代码

UPDATE Products SET Inactive="X" WHERE chkBox="True"

HTML

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Customer_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ProductID" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellPadding="3" CellSpacing="1" GridLines="None">
            <Columns>
                <asp:CommandField ShowEditButton="True" />
                <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox ID="chkRow" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
                <asp:BoundField DataField="ProductID" HeaderText="ProductID" ReadOnly="True" SortExpression="ProductID" InsertVisible="False" />
                <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
                <asp:BoundField DataField="SupplierID" HeaderText="SupplierID" SortExpression="SupplierID" />
                <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" SortExpression="CategoryID" />
                <asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" SortExpression="QuantityPerUnit" />
                <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
                <asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" />
                <asp:BoundField DataField="UnitsOnOrder" HeaderText="UnitsOnOrder" SortExpression="UnitsOnOrder" />
                <asp:BoundField DataField="ReorderLevel" HeaderText="ReorderLevel" SortExpression="ReorderLevel" />
                <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued" SortExpression="Discontinued" />
                <asp:BoundField DataField="Inactive" HeaderText="Inactive" SortExpression="Inactive" />
            </Columns>
            <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
            <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
            <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
            <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
            <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#594B9C" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#33276A" />
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:NorthWindConnectionString %>"
        DeleteCommand=
        "DELETE FROM [Products] WHERE [ProductID] = @ProductID"
        InsertCommand=
        "INSERT INTO [Products] ([ProductName], [SupplierID], [CategoryID], [QuantityPerUnit], [UnitPrice], [UnitsInStock], [UnitsOnOrder], [ReorderLevel], [Discontinued], [Inactive]) VALUES (@ProductName, @SupplierID, @CategoryID, @QuantityPerUnit, @UnitPrice, @UnitsInStock, @UnitsOnOrder, @ReorderLevel, @Discontinued, @Inactive)"
        SelectCommand=
        "SELECT * FROM [Products]"
        UpdateCommand=
        "UPDATE [Products] SET [ProductName] = @ProductName, [SupplierID] = @SupplierID, [CategoryID] = @CategoryID, [QuantityPerUnit] = @QuantityPerUnit, [UnitPrice] = @UnitPrice, [UnitsInStock] = @UnitsInStock, [UnitsOnOrder] = @UnitsOnOrder, [ReorderLevel] = @ReorderLevel, [Discontinued] = @Discontinued, [Inactive] = @Inactive WHERE [ProductID] = @ProductID">
        <DeleteParameters>
        <asp:Parameter Name="ProductID" Type="Int32" />
        </DeleteParameters>
        <UpdateParameters>
        <asp:Parameter Name="ProductName" Type="String" />
        <asp:Parameter Name="SupplierID" Type="Int32" />
        <asp:Parameter Name="CategoryID" Type="Int32" />
        <asp:Parameter Name="QuantityPerUnit" Type="String" />
            <asp:Parameter Name="UnitPrice" Type="Decimal" />
            <asp:Parameter Name="UnitsInStock" Type="Int16" />
            <asp:Parameter Name="UnitsOnOrder" Type="Int16" />
            <asp:Parameter Name="ReorderLevel" Type="Int16" />
            <asp:Parameter Name="Discontinued" Type="Boolean" />
            <asp:Parameter Name="Inactive" Type="String" />
            <asp:Parameter Name="ProductID" Type="Int32" />
        </UpdateParameters>
        <InsertParameters>
        <asp:Parameter Name="ProductName" Type="String" />
        <asp:Parameter Name="SupplierID" Type="Int32" />
        <asp:Parameter Name="CategoryID" Type="Int32" />
            <asp:Parameter Name="QuantityPerUnit" Type="String" />
            <asp:Parameter Name="UnitPrice" Type="Decimal" />
            <asp:Parameter Name="UnitsInStock" Type="Int16" />
            <asp:Parameter Name="UnitsOnOrder" Type="Int16" />
            <asp:Parameter Name="ReorderLevel" Type="Int16" />
            <asp:Parameter Name="Discontinued" Type="Boolean" />
            <asp:Parameter Name="Inactive" Type="String" />
        </InsertParameters>
    </asp:SqlDataSource>

        <asp:Button ID="ASPda" runat="Server" Text="Deactivate ASP" OnClick="Deactivate"/>
        </form>

    <p>
        &nbsp;</p>
</body>
</html>

我要运行停用命令的特定按钮。

<asp:Button ID="ASPda" runat="Server" Text="Deactivate ASP" OnClick="Deactivate"/>

【问题讨论】:

  • 什么意思..你想怎么创建存储过程?
  • 好吧,我只是在寻求帮助,从我的网站中运行 SQL 代码,但是如果我确实需要通过创建存储过程来解决这个问题,那么任何帮助都将不胜感激。跨度>

标签: c# html asp.net sql-server


【解决方案1】:

您对前端代码和 SQL 代码感到困惑。

你的 SQL 伪代码应该是这样的:

UPDATE Products SET Active = 0 WHERE ProductID = @ProductID

上面的 SQL 查询会将 Active 列设置为 0,其中 ProductID 与您从应用程序传递的那个匹配(当然只需将其调整为实际的列名称和值)。

然后在您的GridView TemplateField ItemTemplate 上,添加此标记:

&lt;asp:HiddenField ID="hfProdID" runat="server" Value='&lt;%#Eval("ProductID")%&gt;' /&gt;

然后在你的按钮点击事件上,

    foreach (GridViewRow rw in GridView.Rows) //Loop through all the rows in the GridView
    {
        if(rw.RowType == DataControlRowType.DataRow) //Checks if current row in the loop is a valid DataRow, not a Header or Footer row (which doesn't include the CheckBox and the data)
        {
            CheckBox cbProd = (CheckBox)rw.Cells[0].FindControl("chkRow"); //Finds the checkbox in the first column

            HiddenField hfProd = (HiddenField)rw.Cells[0].FindControl("hfProdID"); //Finds the HiddenField in the first column where ProductID is stored
            if(cbProd.Checked == true)  //Checks if the current checkbox is selected, if yes, execute the UPDATE query by passing the Product ID as the parameter.
            {
                string sqlConnStr = ("put actual connection string here");
                string sqlCmdStr = ("UPDATE Products SET Active = 0 WHERE ProductID = @ProductID"); //UPDATE query
                using(SqlConnection sqlConn = new SqlConnection(sqlConnStr))
                {
                    using(SqlCommand sqlCmd = new SqlCommand(sqlCmdStr, sqlConn))
                    {
                        sqlConn.Open();
                        sqlCmd.Parameters.Clear();
                        sqlCmd.Parameters.AddWithValue("ProductID", hfProd.Value); //Product ID saved in HiddenField
                        sqlCmd.ExecuteNonQuery();
                        sqlConn.Close();
                    }
                }
            }
        }
    }

【讨论】:

  • 如您所知,我对 C# 和 SQL 还很陌生,所以如果让我感到沮丧,我深表歉意。您在哪里说 然后在您的按钮单击事件中, ,我该如何添加它。我是在 C# 中添加一个过程/函数还是将它添加到 ASP.NET 中?
  • 在设计视图中,您需要双击您的按钮,它会将您重定向到代码后面,将创建一个ASPda_Click 事件。您需要复制粘贴并根据需要调整我提供的代码。
  • 我根据我的需要编辑了你的代码。现在我收到很多错误说明 ;预期} 预期。 您给我的 HiddenField 标记也会返回此错误:System.Web.UI.WebControls.DataControlFieldCollection must have items of type 'System.Web.UI .WebControls.DataControlField'。 “asp:HiddenField”的类型为“System.Web.UI.WebControls.HiddenField”。
  • 哦,我的错,我还以为是 vb.net。我会把它转换成 c#。
  • 您声明我必须插入存储过程的名称,但是,在我问的问题中,由于某种原因我无法创建存储过程,在 SQL Server 中没有这样做的选项管理工作室。当我右键单击对象资源管理器中的存储过程文件夹时,菜单上根本没有任何选项。
【解决方案2】:

试试这个:

 public static DataTable GetData()
        {
            String callProcedure = "exec my_proc";
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection("connection string here!"))
            {
                con.Open();
                using (SqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = callProcedure;
                    cmd.CommandType = CommandType.StoredProcedure;
                    using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
                    {
                        adp.Fill(dt);
                        return dt;
                    }
                }
            }
        }

【讨论】:

  • 我应该添加什么来代替基于此的连接字符串:ConnectionString="&lt;%$ ConnectionStrings:NorthWindConnectionString %&gt;"?
  • 是来自 app.config 的连接字符串吗?
  • 我没有任何 app.config 文件,但那里的连接字符串是由 Visual Studio 自动生成的,并且到目前为止已经连接到数据库。它直接取自 ASP.NET 代码
  • 尝试将您的连接分配给一个字符串 str = 'your connection string here' 然后调试并检查 str 是否是您连接的正确字符串值。然后放到new SqlConnection(str)中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-13
  • 1970-01-01
  • 2021-07-15
  • 1970-01-01
相关资源
最近更新 更多