【问题标题】:Store procedure select from two different table to a grid view存储过程从两个不同的表中选择到网格视图
【发布时间】:2013-09-03 07:59:17
【问题描述】:

我正在寻求一些我无法解决的问题的帮助。

我创建了一个存储过程来从名为“申请者”的表中选择数据

效果很好

这是下面的代码:

    USE [Josons]
    GO
    /****** Object: StoredProcedure [dbo].[PROC_GETALLAPPLICANTS] Script Date: 09/03/2013 10:50:58 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    -- Batch submitted through debugger: SQLQuery25.sql|7|0|C:\Users\supportadmin\AppData\Local\Temp\~vs29E1.sql


    ALTER PROCEDURE [dbo].[PROC_GETALLAPPLICANTS]
    AS
    BEGIN
    select ID,FIRSTNAME,LASTNAME,APPLYDATE from APPLICANT order by ID Asc
    END

我添加了一个名为“AF”的新表,这两个表与一个唯一列相关:“applicant_id”

如何使存储过程从 2 个表中选择并以相同的顺序“ID Asc”显示在一个网格视图中

编辑:

aspx 文件:

    <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPages/MainMasterPage.master"
    AutoEventWireup="true" CodeFile="HR.aspx.cs" Inherits="Pages_HR" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div>
    <asp:Button ID="btnLogout" CssClass="btnLogoutStyle" runat="server" 
        Text="Logout" onclick="btnLogout_Click" />
</div>

        <div class="divgvDisplayAllApplicantsStyle">
            <asp:GridView 
                ID="gvDisplayAllApplicants"
                CssClass="gridviewstyle" 
                runat="server"     
                OnRowDataBound="gvDisplayAllApplicants_RowDataBound"
                AllowPaging="true"
                PageSize="10"
                OnPageIndexChanging="gvDisplayAllApplicants_PageIndexChanging"
                OnSelectedIndexChanged="gvDisplayAllApplicants_SelectedIndexChanged"
                DataKeyNames="ID" 
                Width="940"
                AutoGenerateColumns="false">
                <Columns>
                    <asp:ButtonField CommandName="Select" Visible="false" /> 
                    <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" />
                    <asp:TemplateField HeaderText="AF #">
                        <ItemTemplate>
                            <%# Eval("AF")%>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="First Name">
                        <ItemTemplate>
                            <%# Eval("FIRSTNAME")%>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Last Name">
                        <ItemTemplate>
                            <%# Eval("LASTNAME")%>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Apply Date">
                        <ItemTemplate>
                            <%# Eval("APPLYDATE")%>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
        </div>

</asp:Content>

和 aspx.cs 文件:

    public partial class Pages_HR : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["DisplaySelectedApplicant"] = "DisplaySelectedApplicant";

            try
            {
                if (Session["HR"].ToString() == "" && Request.QueryString["queryStringBackButton"].ToString() == null)
                {
                    Session["DisplaySelectedApplicant"] = "";
                    Session["HR"] = "";
                    Response.Redirect("LoginPage.aspx");

                }
            }
            catch (NullReferenceException)
            {
                Response.Redirect("LoginPage.aspx");

            }

        }

        FillApplicantGridView();
    }

    #region METHODS
    public void FillApplicantGridView()
    {
        string connstr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
        using (SqlConnection sqlconnection = new SqlConnection(connstr))
        {
            sqlconnection.Open();
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "PROC_GETALLAPPLICANTS";
                cmd.Connection = sqlconnection;

                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd);
                DataTable datatable = new DataTable();
                sqlDataAdapter.Fill(datatable);

                gvDisplayAllApplicants.DataSource = datatable;
                gvDisplayAllApplicants.DataBind();

                sqlconnection.Close();
            }
        }
    }
    protected void gvDisplayAllApplicants_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // Get reference to button field in the gridview.  
                LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
                string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "Select$" + e.Row.RowIndex);
                e.Row.Style["cursor"] = "hand";
                e.Row.Attributes["onclick"] = _jsSingle;

                e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#93A3B0'; this.style.color='White'; this.style.cursor='pointer'");

                e.Row.Attributes.Add("onmouseout", String.Format("this.style.color='Black';this.style.backgroundColor='White';", gvDisplayAllApplicants.RowStyle.BackColor.ToKnownColor()));



            }
        }
    }
    protected void gvDisplayAllApplicants_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridViewRow selectedRow = gvDisplayAllApplicants.SelectedRow;
        int rowIndex = selectedRow.RowIndex;
        string Applicant_ID = gvDisplayAllApplicants.DataKeys[rowIndex].Values["ID"].ToString();
        Response.Redirect("DisplaySelectedApplicant.aspx?ID=" + Applicant_ID);

    }
    protected override void Render(HtmlTextWriter writer)
    {
        foreach (GridViewRow row in gvDisplayAllApplicants.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                ClientScript.RegisterForEventValidation(((LinkButton)row.Cells[0].Controls[0]).UniqueID, "Select$" + row.RowIndex);
            }
        }
        base.Render(writer);
    }
    protected void gvDisplayAllApplicants_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvDisplayAllApplicants.PageIndex = e.NewPageIndex;
        gvDisplayAllApplicants.ShowFooter = false;
        gvDisplayAllApplicants.EditIndex = -1;
        FillApplicantGridView();
    }



    #endregion



    protected void btnLogout_Click(object sender, EventArgs e)
    {
        Response.Redirect("LoginPage.aspx");
    }
}


Thanks,

【问题讨论】:

    标签: asp.net sql gridview stored-procedures


    【解决方案1】:

    如果您想要两个表都有 application_id 的所有记录,请使用 INNER JOIN...

    SELECT  ap.ID ,
            ap.FIRSTNAME ,
            ap.LASTNAME ,
            ap.APPLYDATE ,
            AF.FieldNames
    FROM    APPLICANT ap
            INNER JOIN AF ON ap.applicant_id = AF.applicant_id
    ORDER BY ap.ID ASC
    

    如果要返回所有的申请者,即使AF中没有对应关系,那么使用LEFT JOIN...

    SELECT  ap.ID ,
            ap.FIRSTNAME ,
            ap.LASTNAME ,
            ap.APPLYDATE ,
            AF.FieldNames
    FROM    APPLICANT ap
            LEFT JOIN AF ON ap.applicant_id = AF.applicant_id
    ORDER BY ap.ID ASC
    

    没有记录时使用 ISNULL 的示例...

    SELECT  ap.ID ,
            ap.FIRSTNAME ,
            ap.LASTNAME ,
            ap.APPLYDATE ,
            ISNULL(AF.AppFormCourseName, 'No Application as of yet')
    FROM    APPLICANT ap
            LEFT JOIN AF ON ap.applicant_id = AF.applicant_id
    ORDER BY ap.ID ASC
    

    考虑将 AF 表也称为更好的名称,我猜它可能是 ApplicationForm

    在此处查看Inner JoinLeft Join 的说明。

    【讨论】:

    • 在asp端还是一样吗?是的,我会把名字改成申请表
    • 是的,这不会改变。您从 AF 中提取哪些字段,是否有可能在没有 AF 记录的情况下在 Application 中有记录?如果是这样,您可以在 AF 字段上使用 ISNULL 来返回比 null 更好的数据,我会更新您确认的答案。
    • 不,它总是有记录。我从 AF 中提取 AF 列,其余部分从 APPLICANT 中提取:id、firstname、last name、applydate。
    • 我将添加 aspx 和 aspx.cs 文件。
    • @EddyAkl,在这种情况下,请坚持使用Inner Join
    【解决方案2】:
      ALTER PROCEDURE [dbo].[PROC_GETALLAPPLICANTS] AS 
    BEGIN 
    select a.ID,a.FIRSTNAME,a.LASTNAME,a.APPLYDATE,af.* from APPLICANT a join AF af on  a.applicant_id = af.applicant_id  order by a.ID Asc 
    END
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-01
      • 2022-01-08
      相关资源
      最近更新 更多