GridView不在面板内显示数据

时间:2016-05-11 14:46:32

标签: c# sql asp.net visual-studio gridview

我正在开发一个搜索人员的系统,然后在GridView中显示符合相关搜索条件的所有人,但没有显示任何数据,这真让我感到沮丧。 这是来自PatientSearch.aspx的面板/网格视图

<asp:UpdatePanel ID="pnlUpdate" runat="server">
        <ContentTemplate>
            <asp:Panel ID="pnlResults" runat="server" ScrollBars="Auto" >
                <asp:GridView ID="gvSearch" runat="server" Font-Names = "Arial" Font-Size = "11pt" ForeColor = "#000000"
                    onselectedindexchanged="gvSearch_SelectedIndexChanged" AutoGenerateColumns = "false" DataKeyNames="patientid" AllowPaging = "true"
                    OnPageIndexChanging = "OnPaging" PageSize = "10" Width = "100%" HeaderStyle-BackColor = "#465c71" HeaderStyle-ForeColor = "#ffffff"> 

                    <Columns>
                        <%--Creates a select button that appear at the start of the grid view--%>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:LinkButton Text="Select" ID="lnkSelect" runat="server" CommandName="Select" />
                            </ItemTemplate>
                        </asp:TemplateField>

                        <asp:TemplateField HeaderText="HC Number" ItemStyle-Wrap="False">
                            <ItemTemplate>
                                <%--This will be the first field to appear beside the select button--%>
                                <asp:Label ID="lblHCNum" Text='<%# Eval("HC_Number") %>' runat="server" />
                            </ItemTemplate>
                        </asp:TemplateField>
                            <%--Bound fields will place them in a specific order--%>
                            <asp:BoundField DataField = "PatientNumber" HeaderText="Patient Number"/>
                            <asp:BoundField DataField = "Surname" HeaderText="Surname"/>
                            <asp:BoundField DataField = "Forename" HeaderText="Forename"/>
                            <asp:BoundField DataField = "ReferredBy" HeaderText="Consultant" ItemStyle-Wrap="False" />
                            <asp:BoundField DataField = "Sex" HeaderText="Sex"/>
                            <asp:BoundField DataField = "DateOfBirth" HeaderText = "Date Of Birth" DataFormatString="{0:d}" />
                            <asp:BoundField DataField = "AppointmentDate" HeaderText = "Appointment Date" DataFormatString="{0:d}" />

                    </Columns> 
                </asp:GridView>
            </asp:Panel>
        </ContentTemplate>
    <Triggers>
    <asp:AsyncPostBackTrigger ControlID="gvSearch" />
    </Triggers>
    </asp:UpdatePanel>

此代码来自GridView等的PatientSearch.aspx.cs

 public partial class PatientSearch : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //As this is the first page the user will have contact with when logged in this is where the limits of what they can and cannot do 
        //Are created to be used on all pages

        //Open connection to database
        string constr = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))

        {
            //Select columns required 
            using (SqlCommand cmd = new SqlCommand("SELECT [RoleName], [AddPermission], [EditPermission], [DeletePermission] FROM aspnet_Roles"))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        //Fill required columns into datatable
                        sda.Fill(dt);

                        //Create stringbuilder to store RoleNames
                        StringBuilder addPermission = new StringBuilder();
                        StringBuilder editPermission = new StringBuilder();
                        StringBuilder deletePermission = new StringBuilder();

                        //Iterate through the datatable and add each correct row to the stringbuilder
                        for (int i = dt.Rows.Count - 1; i >= 0; i--)
                        {
                            DataRow dr = dt.Rows[i];

                            //only add the necessary rows to the string builder
                            if (dr["AddPermission"].ToString() == "True")
                                addPermission.AppendLine(string.Join(",", dr.ItemArray));

                            if (dr["EditPermission"].ToString() == "True")
                                editPermission.AppendLine(string.Join(",", dr.ItemArray));

                            if (dr["DeletePermission"].ToString() == "True")
                                deletePermission.AppendLine(string.Join(",", dr.ItemArray));
                        }

                        //Remove the unnecessary data from the string
                        addPermission.Replace(",True", ""); addPermission.Replace(",False", "");
                        editPermission.Replace(",True", ""); editPermission.Replace(",False", "");
                        deletePermission.Replace(",True", ""); deletePermission.Replace(",False", "");

                        //Convert stringbuilder to string to allow it to be compared
                        var add = addPermission.ToString();
                        var edit = editPermission.ToString();
                        var delete = deletePermission.ToString();

                        //Retrieve all roles the current user has access to
                        var userRoles = Roles.GetRolesForUser(User.Identity.Name);

                        if (!userRoles.Any(u => add.Contains(u)))
                        {
                            btnNewRecord.Enabled = false;
                        }

                        //Store what permissions are granted to which roles
                        Session["AddPermission"] = add;
                        Session["EditPermission"] = edit;
                        Session["DeletePermission"] = delete;
                    }
                }
            }
        }

        DataSet ds = (DataSet)Session["DS"];

       // if (ds == null)
        //{
            //Make the menu inaccessable if no record has been selected, Due to menu being ambiguous System.Web.UI.WebControls is required
            //System.Web.UI.WebControls.Menu MyMasterMenu = (System.Web.UI.WebControls.Menu)Master.FindControl("NavigationMenu");
            //MyMasterMenu.Visible = false;
        //}

        //Hide the export buttons if the gridview is empty
        if (gvSearch.DataSource == null)
        {
            //imgWord.Visible = false; 
            imgExcel.Visible = false;
            lblExport.Visible = false;
        }
        else
        {
            //imgWord.Visible = true; 
            imgExcel.Visible = true;
            lblExport.Visible = true;
        }

        //Hide label that catches any errors from user
        lblErrors.Visible = false;

        if (Session["RecordSuccessfullyDeleted"] != null)
        {
            //Message that has been passed from another page, informs the user that the record has ben successfully deleted
            string deletedID = Session["RecordSuccessfullyDeleted"].ToString();
            lblErrors.Text = deletedID + " Succesfully Deleted!";

            //calls the popup to display a notification
            dvMsg.Visible = true;
            lblMsg.Text = "" + lblErrors.Text;

            //To prevent message appearing multiple times
            Session["RecordSuccessfullyDeleted"] = null;
        }
        else
        {
            dvMsg.Visible = false;
        }
    }

    //Tells the page what to do once the user has selected a patient
    protected void gvSearch_SelectedIndexChanged(object sender, EventArgs e)
    {

        DataSet ds = new DataSet();
        int index = gvSearch.SelectedIndex;

        string strConString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
        SqlConnection myConnect = new SqlConnection(strConString);
        myConnect.ConnectionString = strConString;

        string strCommandText = "prcPersonalSelectedByPatientIdRetrieve";

        try
        {
            SqlCommand sqlCmd = new SqlCommand(strCommandText, myConnect);
            sqlCmd.CommandType = CommandType.StoredProcedure;

            sqlCmd.Parameters.Add(new SqlParameter("@PatientNumber", gvSearch.DataKeys[index].Value.ToString()));

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = sqlCmd;
            da.Fill(ds, "personal");

            //Needed to reset the clinical eval page for newly selected patient
            Session["NDS"] = null;
        }

        catch (Exception fe)
        {
            lblMoreErrors.Text = "Error: " + fe.Message;
        }

        try
        {
            //Assigns the selected patients details to the dataset and redirects the user to the personal page
            Session["DS"] = ds;
            Response.Redirect("~/UserPages/PatientDetails.aspx");
        }

        catch (Exception er)
        {
            lblErrors.Text = "Error: " + er.Message;
        }
    }

    //Tells the gridview what to do when the page change is selected
    protected void OnPaging(object sender, GridViewPageEventArgs e)
    {
        this.DataBindSearch();
        gvSearch.PageIndex = e.NewPageIndex;
        gvSearch.DataBind();
    }

    protected void BtnResetSearch(object sender, EventArgs e)
    {
        //Deletes all current criteria enetered and refreshes the page
        Session["ViewState"] = null;
        Response.Redirect("~/UserPages/PatientSearch.aspx");
    }

    protected void BtnSearch(object sender, EventArgs e)
    {
        //Sets the panel properties after the button is clicked, this helps avoid the empty white 
        //space at the bottom if the property is assigned when nothing is there
        pnlResults.Style.Add("height", "500px");
        this.DataBindSearch();
    }
    protected void BtnAddPatient(object sender, EventArgs e)
    {
        Session.Remove("DS");
        Response.Redirect("~/UserPages/AddPatient.aspx", false);
    }
    protected void DataBindSearch()
    {
        DataSet ds = new DataSet();

        string strConString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
        SqlConnection myConnect = new SqlConnection(strConString);
        myConnect.ConnectionString = strConString;

        string strCommandText = "prcPersonalByPatientIdSelect";

        //Now allows partial searches eg. Surname: M will return all surnames with M in it
        try
        {
            SqlCommand sqlCmd = new SqlCommand(strCommandText, myConnect);
            sqlCmd.CommandType = CommandType.StoredProcedure;

            if (txtPatientNumber.Text != "")
            {
                sqlCmd.Parameters.Add(new SqlParameter("@PatientNumber", txtPatientNumber.Text));
            }

            if (txtHCNumber.Text != "___-___-____")
            {
                sqlCmd.Parameters.Add(new SqlParameter("@HC_Number", txtHCNumber.Text));
            }

            if (txtPatientSurname.Text != "")
            {
                sqlCmd.Parameters.Add(new SqlParameter("@Surname", txtPatientSurname.Text));
            }

            if (txtPatientFirstName.Text != "")
            {
                sqlCmd.Parameters.Add(new SqlParameter("@Forename", txtPatientFirstName.Text));
            }

            if (dpdConsultant.Text != "")
            {
                sqlCmd.Parameters.Add(new SqlParameter("@Consultant", dpdConsultant.Text));
            }

            if (dpdSex.Text != "")
            {
                sqlCmd.Parameters.Add(new SqlParameter("@Sex", dpdSex.Text));
            }


            //Date of Birth Search
            if (txtDateOfBirth.Text != "")
            {
                //Required for use of between dates
                string dateDoB = txtDateOfBirth.Text;
                DateTime date = Convert.ToDateTime(dateDoB);
                sqlCmd.Parameters.Add(new SqlParameter("@DateOfBirth", date));
            }
            if (txtDateOfBirthTo.Text != "")
            {
                if (txtDateOfBirthTo.Text == "*")
                {
                    //Carries out the funtion of the wildcard
                    DateTime now = DateTime.Now;
                    sqlCmd.Parameters.Add(new SqlParameter("@DateOfBirthEnd", now));
                }
                else
                {
                    //Required for use of between dates
                    string dateDoB = txtDateOfBirthTo.Text;
                    DateTime date = Convert.ToDateTime(dateDoB);
                    sqlCmd.Parameters.Add(new SqlParameter("@DateOfBirthEnd", date));
                }
            }

            //Diagnosis Date Search
            if (txtDiagnosisDate.Text != "")
            {
                //Required for use of between dates
                string dateDD = txtDiagnosisDate.Text;
                DateTime date = Convert.ToDateTime(dateDD);
                sqlCmd.Parameters.Add(new SqlParameter("@DiagnosisDate", date));
            }
            if (txtDiagnosisDateTo.Text != "")
            {
                if (txtDiagnosisDateTo.Text == "*")
                {
                    //Carries out the funtion of the wildcard
                    DateTime now = DateTime.Now;
                    sqlCmd.Parameters.Add(new SqlParameter("@DiagnosisDateEnd", now));
                }
                else
                {
                    //Required for use of between dates
                    string dateDD = txtDiagnosisDateTo.Text;
                    DateTime date = Convert.ToDateTime(dateDD);
                    sqlCmd.Parameters.Add(new SqlParameter("@DiagnosisDateEnd", date));
                }
            }

            //Examination Date Search
            if (txtAppointmentDate.Text != "")
            {
                //Required for use of between dates
                string dateED = txtAppointmentDate.Text;
                DateTime date = Convert.ToDateTime(dateED);
                sqlCmd.Parameters.Add(new SqlParameter("@AppointmentDate", date));
            }

            if (txtAppointmentDateEnd.Text != "")
            {
                if (txtAppointmentDateEnd.Text == "*")
                {
                    //Carries out the funtion of the wildcard
                    DateTime now = DateTime.Now;
                    sqlCmd.Parameters.Add(new SqlParameter("@AppointmentDateEnd", now));
                }
                else
                {
                    //Required for use of between dates
                    string dateAD = txtAppointmentDateEnd.Text;
                    DateTime date = Convert.ToDateTime(dateAD);
                    sqlCmd.Parameters.Add(new SqlParameter("@AppointmentDateEnd", date));
                }
            }


            //Age at Examination Search
            if (txtAgeAtExamination.Text != "")
            {
                //Required for use of between dates
                string Age = txtAgeAtExamination.Text;
                DateTime date = Convert.ToDateTime(Age);
                sqlCmd.Parameters.Add(new SqlParameter("@Age", date));
            }

            if (txtAgeAtExaminationTo.Text != "")
            {
                if (txtAgeAtExamination.Text == "*")
                {
                    //Carries out the funtion of the wildcard
                    DateTime now = DateTime.Now;
                    sqlCmd.Parameters.Add(new SqlParameter("@AgeEnd", now));
                }
                else
                {
                    //Required for use of between dates
                    string Age = txtAgeAtExamination.Text;
                    DateTime date = Convert.ToDateTime(Age);
                    sqlCmd.Parameters.Add(new SqlParameter("@AgeEnd", date));
                }
            }

            //EXAMINATION CHECKBOXES
            //Full-field ERG Checkbox
            if (chkERG.Checked)
            {
                sqlCmd.Parameters.Add(new SqlParameter("@FullField_ERG", chkERG.Checked));
            }

            //Pattern ERG Checkbox
            if (chkPERG.Checked)
            {
                sqlCmd.Parameters.Add(new SqlParameter("@PatternERG", chkPERG.Checked));
            }

            //EOG Checkbox
            if (chkEOG.Checked)
            {
                sqlCmd.Parameters.Add(new SqlParameter("EOG", chkEOG.Checked));
            }

            //Pattern VEP Checkbox
            if (chkPVEP.Checked)
            {
                sqlCmd.Parameters.Add(new SqlParameter("@PatternVEP", chkPVEP.Checked));
            }

            //Flash VEP Checkbox
            if (chkFVEP.Checked)
            {
                sqlCmd.Parameters.Add(new SqlParameter("@FlashVEP", chkFVEP.Checked));
            }

            //Comb VEP/ERG Checkbox
            if (chkVEPERG.Checked)
            {
                sqlCmd.Parameters.Add(new SqlParameter("@CombVEP_ERG", chkVEPERG.Checked));
            }

            //Binoc PVEP Checkbox
            if (chkBPVEP.Checked)
            {
                sqlCmd.Parameters.Add(new SqlParameter("@BinocPVEP", chkBPVEP.Checked));
            }


            //ATTENDANCE
            if (dpdByAttendance.Text != "")
            {
                sqlCmd.Parameters.Add(new SqlParameter("@Attended", dpdByAttendance.Text));
            }

            if (dpdTestedBy.Text != "")
            {
                sqlCmd.Parameters.Add(new SqlParameter("@TestedBy", dpdTestedBy.Text));
            }


            //
            //Awaiting Technical Report
            if (chkAwaitingTechnicalReport.Checked)
            {
                sqlCmd.Parameters.Add(new SqlParameter("@AwaitingTechnicalReport", chkAwaitingTechnicalReport.Checked));
            }

            //Feedback Patients
            if (chkFeedbackPatients.Checked)
            {
                sqlCmd.Parameters.Add(new SqlParameter("@FeedbackPatients ", chkFeedbackPatients.Checked));
            }

            //Interesting Patients
            if (chkInterestingPatients.Checked)
            {
                sqlCmd.Parameters.Add(new SqlParameter("@InterestingPatients", chkInterestingPatients.Checked));
            }

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = sqlCmd;
            da.Fill(ds, "personal");
            DataTable dt = new DataTable();
            da.Fill(dt);

            //Counts the number of results found
            lblResults.Text = "Results Found: " + ds.Tables.Cast<DataTable>().Sum(x => x.Rows.Count).ToString();
            //Finally, all results matching the criteria will be placed into the gridview
            gvSearch.DataBind();

            //Adds the export button if more than zero results are found
            if (ds.Tables.Cast<DataTable>().Sum(x => x.Rows.Count) > 0)
            {
                //imgWord.Visible = true; 
                imgExcel.Visible = true;
                lblExport.Visible = true;
            }

            Session["CurrentData"] = dt;
        }

        catch (Exception fe)
        {
            lblErrors.Text = "Error: " + fe.Message;
        }
    }

所有帮助对我来说都非常有价值,因为它让我非常沮丧。

提前致谢

P.S,我已经编辑并添加了整个代码,看看是否有任何明显的错过。

1 个答案:

答案 0 :(得分:0)

您需要将数据源分配给gridview,是否设置了

 gvSearch.DataSource=(DataSet) Session["DS"];
 gvSearch.Databind();