简体   繁体   中英

Pass data to stored proc and return data to gridview

I'm writing a asp .net webpage to pass textbox data to a stored proc and return a gridview of data on a button click. I've started writing the code but I'm getting confused as to how I allow the items to control the actions on the page. Ie have the button click pass the field values to a stored proc to get data back.

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>MSS Archived Data</title>

    <script language="javascript" type="text/javascript">
// <!CDATA[
// ]]>
    </script>

</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>
                        <asp:Label ID="Label1" runat="server" Text="First Name: "></asp:Label>
                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                        <asp:Label ID="Label2" runat="server" Text="Last Name: "></asp:Label>
                        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                        <asp:Label ID="Label3" runat="server" Text="Street: "></asp:Label>
                        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="Label4" runat="server" Text="City: "></asp:Label>
                        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
                        <asp:Label ID="Label5" runat="server" Text="State: "></asp:Label>
                        <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
                        <asp:Label ID="Label6" runat="server" Text="Zip: "></asp:Label>
                        <asp:TextBox ID="TextBox6" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="Button1" runat="server" Text="Search" OnClick="Button1_Click" />
                    </td>                    
                </tr>
            </table>
            <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
                DataKeyNames="actID" DataSourceID="PersEWD_Database">
                <Columns>
                    <asp:BoundField DataField="actID" HeaderText="actID" ReadOnly="True" InsertVisible="False"
                        SortExpression="actID"></asp:BoundField>
                    <asp:BoundField DataField="actLogCreateDate" HeaderText="actLogCreateDate" SortExpression="actLogCreateDate">
                    </asp:BoundField>
                    <asp:BoundField DataField="actCustomerID" HeaderText="actCustomerID" SortExpression="actCustomerID">
                    </asp:BoundField>
                    <asp:BoundField DataField="actCampaignID" HeaderText="actCampaignID" SortExpression="actCampaignID">
                    </asp:BoundField>
                    <asp:BoundField DataField="actActionDate" HeaderText="actActionDate" SortExpression="actActionDate">
                    </asp:BoundField>
                    <asp:BoundField DataField="actActionCode" HeaderText="actActionCode" SortExpression="actActionCode">
                    </asp:BoundField>
                    <asp:BoundField DataField="actRelevantInfo" HeaderText="actRelevantInfo" SortExpression="actRelevantInfo">
                    </asp:BoundField>
                    <asp:BoundField DataField="actUnderwriter" HeaderText="actUnderwriter" SortExpression="actUnderwriter">
                    </asp:BoundField>
                    <asp:BoundField DataField="actAmount" HeaderText="actAmount" SortExpression="actAmount">
                    </asp:BoundField>
                    <asp:BoundField DataField="actPolicyType" HeaderText="actPolicyType" SortExpression="actPolicyType">
                    </asp:BoundField>
                    <asp:BoundField DataField="actPolicyNumber" HeaderText="actPolicyNumber" SortExpression="actPolicyNumber">
                    </asp:BoundField>
                    <asp:BoundField DataField="actReasonCode" HeaderText="actReasonCode" SortExpression="actReasonCode">
                    </asp:BoundField>
                    <asp:BoundField DataField="actSSN" HeaderText="actSSN" SortExpression="actSSN"></asp:BoundField>
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data.Odbc;
using System.Web.Configuration;

public partial class _Default : System.Web.UI.Page
{
    DataSet ds = new DataSet();

    //Here we declare the parameter which we have to use in our application
    SqlCommand cmd = new SqlCommand();
    SqlParameter sp1 = new SqlParameter();
    SqlParameter sp2 = new SqlParameter();
    SqlParameter sp3 = new SqlParameter();
    SqlParameter sp4 = new SqlParameter();
    SqlParameter sp5 = new SqlParameter();
    SqlParameter sp6 = new SqlParameter();

    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //string myConnection = "dsn=dsnNAME";
        string serverName = "serverName";
        string dbName = "dbName";
        string storedProcName = "";
        string parameterName = "@RecordType";
        int parameterValue = 0;
        string myConnString = "DRIVER={SQL Server};SERVER="+serverName+";Trusted_connection=yes;DATABASE="+dbName+";";




        OdbcConnection myConnection = new OdbcConnection(myConnString);
        myConnection.Open();
        //myConnection.Connection = myConnection;
        myConnection.CommandType = CommandType.StoredProcedure;
        myConnection.CommandText = "{call " + storedProcName + " (?, ?, ?, ?, ?, ?) }";
        cmd.Parameters.Add("@fName", SqlDbType.VarChar).Value = TextBox1.Text;
        cmd.Parameters.Add("@lName", SqlDbType.VarChar).Value = TextBox2.Text;
        cmd.Parameters.Add("@street", SqlDbType.VarChar).Value = TextBox3.Text;
        cmd.Parameters.Add("@city", SqlDbType.VarChar).Value = TextBox4.Text;
        cmd.Parameters.Add("@state", SqlDbType.VarChar).Value = TextBox5.Text;
        cmd.Parameters.Add("@zip", SqlDbType.varchar).Value = TextBox6.Text;

        myConnection.ExecuteNonQuery();
        myConnection.Connection.Close();
    }

}

Thanks

The lifecycle of your data binding looks a little something like this:

  1. Button Click - Your button will trigger a Click event when the user presses it. From here you'll want to call your stored procedure, using the value in the TextBox.

  2. Data Retrieval - You execute your stored procedure using the parameter specified, and get a collection of data elements back. Depending on what version of the .Net Framework you have available, I'd recommend either using TableAdapters (older technology, gives you a table structure that mirrors your database) or use LINQ/Entity Framework (newer technology, give you an object based off of your table and provides a list of those objects based off of the query). LINQ/EF is some amazing stuff, but some dev environments still aren't up to .Net 3.5 yet.

  3. Data Binding - After you get the data back from your stored procedure, you'll set that as the DataSource of your GridView and then call the DataBind method. The GridView control will automatically handle iterating through the data you give it. If you need to do some custom columns/formatting, you'll override the RowDataBound event.

There are a lot of nuances and details to each aspect of this process, but hopefully this gives you the basic understanding of things in which to start with.

You're almost there. You need to set your select command to the name of the stored proc, then set the SelectCommandType to StoredProcedure. Then set the PropertyName of your ControlParameter.

This will set up your GridView to be databound to the value of the text box on postback (button click can cause a postback)

Also set your GridView's DataSourceID to match the ID of your SqlDataSource.

 <asp:SqlDataSource ID="Database" runat="server" ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString %>"
            ProviderName="<%$ ConnectionStrings:Database_ConnectionString.ProviderName %>"
            SelectCommand="dbo.yourstoredproc" SelectCommandType="StoredProcedure"
            OnSelecting="Database_Selecting">
            <SelectParameters>
                <asp:ControlParameter ControlID="Text1" Name="CustomerID" PropertyName="Text" />
            </SelectParameters>
        </asp:SqlDataSource>

A few pointers:

1) Use <asp:textbox id="Text1" runat="server"/> rather than <input name="CustomerID" id="Text1" type="text" /> - note the runat="server" this allows the datasource selectparameters to find its input source.

2) Point your gridview datasourceid to your sqldatasource if that's indeed where the data is coming from. Otherwise, where is "PersEWD_Database" data source defined?

3) Make your sqldatasource sql script return all the fields required to be bound on the grid not just the CustomerID.

4) Remove the empty <script> block unless you need it.

5) Remove OnSelecting="Database_Selecting" unless you need it.

6) Change <asp:Button> onclick() to onclick="ButtonSearch_Click" and implement the ButtonSearch_Click event handler in the code behind to repost the page. You could probably leave the event handler empty if you don't need to do anything other than load the grid with the typed in customer id.

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