admin管理员组

文章数量:1410724

As the title says: I was to be able to do a search bring the search data back into a gridview that has clickable rows and once a row is clicked i will need to grab some info from that row and place it in a new div location on the same page in order to add more information specifically for that row.

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">

    <div class="wrapperHistoricalData"> 
       
        <fieldset style="margin-bottom:5px;margin-top:10px;border-color:#efefef;">

             <legend>Search</legend>
         <%--  <asp:UpdatePanel ID="uPanelTop" runat="server"   >
                <ContentTemplate>--%>
                <div class="divFloatLeft">
                    <asp:TextBox ID="txtStudentFirstName" runat="server"  placeholder="First Name or ID" ></asp:TextBox>
                    <asp:TextBox ID="txtStudentLastName" runat="server"  placeholder="Last Name" ></asp:TextBox>      
                    <asp:DropDownList ID="ddlClinicalType" runat="server"  DataTextField="ClinicalTypeDesc" DataValueField="ClinicalTypeID"  />
                    <asp:Button ID="btnSearch" runat="server" Text="Search"  OnClick="btnSearch_Click" />
                </div>
           
            <asp:RequiredFieldValidator 
                ID="rfvClinicalType" 
                runat="server" 
                ControlToValidate="ddlClinicalType" 
                InitialValue="" 
                ErrorMessage="Please select a Clinical option!" 
                ForeColor="Red" 
                Style="margin-left: 25px;"/>
                     <%-- </ContentTemplate>
                </asp:updatePanel>--%>
        </fieldset>
    </div>
    
    <div class="wrapperHistoricalData">
        <asp:updatePanel ID="uPanelData" runat="server"   >
                  <ContentTemplate>
                        <asp:GridView ID="gvHistoricalData" runat="server" AutoGenerateColumns="false" AllowPaging="True" AllowSorting="True" CssClass="DataEntryGridView" RowStyle-CssClass="GvGrid"  OnRowDataBound="gvHistoricalData_RowDataBound" OnRowCommand="gvHistoricalData_RowCommand">
                             <RowStyle CssClass="rowMain" />
                             <AlternatingRowStyle CssClass="rowAlt" />
                             <HeaderStyle  CssClass="rowHeader" width="100px"/>
                                       <Columns>
                                            
                                           <asp:TemplateField HeaderText="Name" ItemStyle-HorizontalAlign="Center" >
                                                 <ItemStyle CssClass="noBorder"/>
                                                    <ItemTemplate>
                                                        <asp:Label  runat="server" ID="lblName"  Text='<%# Eval("FullName") %>' CssClass="StudentName" />                                                      
                                                    </ItemTemplate>
                                          </asp:TemplateField>
                                             
                                           
                                       </Columns>
                                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                                <EditRowStyle BackColor="#999999" />
                                <FooterStyle BackColor="#5D7B9D" ForeColor="White" Font-Bold="True" />
                                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" Font-Size="15px" />
                                <PagerStyle CssClass="UserMaintUsersPager" BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                                <SortedAscendingCellStyle BackColor="#E9E7E2" />
                                <SortedAscendingHeaderStyle BackColor="#506C8C" />
                                <SortedDescendingCellStyle BackColor="#FFFDF8" />
                                <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                        </asp:GridView>
                  </ContentTemplate>
        </asp:updatePanel>

    </div>
    <div class="divInput" id="divtest">
        <div>   <--- this sint done being built yet but the information will be in here with more input boxes  ---->
            <asp:Label runat="server" ID="lbltest" Text="yeah"></asp:Label>

        </div>
    </div>

Currently when I click the row, it returns an error: "All the headers have been sent" I have left code in t=so you can see what i have tried and still cant get it to work,

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                getClinicalTypes();

            }
         
            // Restore selected row color after postback
            HighlightSelectedRow();
        }

        protected void Search(string fname, string lname, string clinicalType)
        {

           List<StudentInfo> studInfo = new List<StudentInfo>();
            if((Regex.IsMatch(fname, @"\d")) )
            {
                studInfo = CTStudentSearch.ListSearch("I", fname, "", clinicalType);
            }
            else
            {
                studInfo = CTStudentSearch.ListSearch("N", fname, lname, clinicalType);
            }
            
            gvHistoricalData.DataSource = studInfo;
            gvHistoricalData.DataBind();

        }
      
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string searchText = "";
          
            string fname = (!string.IsNullOrWhiteSpace(txtStudentFirstName.Text)) ? txtStudentFirstName.Text : "";
            string lname = (!string.IsNullOrWhiteSpace(txtStudentLastName.Text)) ? txtStudentLastName.Text : "";
            bool clinicalTypeChecked = (ddlClinicalType.SelectedIndex > 0) ? true : false;
            string clinicalType = null;
            if (clinicalTypeChecked == true)
            {
                clinicalType = ddlClinicalType.SelectedValue;

                Search(fname, lname, clinicalType);

            }
           
        }
       

        protected void gvHistoricalData_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onMouseOver", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#5D7B9D';this.style.cursor='pointer';");
                e.Row.Attributes.Add("OnMouseOut", "this.style.backgroundColor=this.originalstyle;");

                // Updated script to prevent row selection if clicking inside an input, button, or link
                //string script = "if(event.srcElement && (event.srcElement.tagName.toLowerCase() === 'input' || event.srcElement.tagName.toLowerCase() === 'button' || event.srcElement.tagName.toLowerCase() === 'a')) return;";
                //e.Row.Attributes["onclick"] = script + Page.ClientScript.GetPostBackClientHyperlink(gvHistoricalData, "Select$" + e.Row.RowIndex);

                // Add a hidden button inside the row to trigger postback
                LinkButton lb = new LinkButton();
                lb.CommandName = "Select";
                lb.CommandArgument = e.Row.RowIndex.ToString();
                lb.Style["display"] = "none"; // Hide the button
                e.Row.Cells[0].Controls.Add(lb);
                // Add OnClientClick event
                lb.OnClientClick = "return showInputDiv(); ";

                // Optionally, set a data attribute to store the row index
                lb.Attributes["data-row-index"] = e.Row.RowIndex.ToString();

                e.Row.Cells[0].Controls.Add(lb);
            }
        }

As the title says: I was to be able to do a search bring the search data back into a gridview that has clickable rows and once a row is clicked i will need to grab some info from that row and place it in a new div location on the same page in order to add more information specifically for that row.

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">

    <div class="wrapperHistoricalData"> 
       
        <fieldset style="margin-bottom:5px;margin-top:10px;border-color:#efefef;">

             <legend>Search</legend>
         <%--  <asp:UpdatePanel ID="uPanelTop" runat="server"   >
                <ContentTemplate>--%>
                <div class="divFloatLeft">
                    <asp:TextBox ID="txtStudentFirstName" runat="server"  placeholder="First Name or ID" ></asp:TextBox>
                    <asp:TextBox ID="txtStudentLastName" runat="server"  placeholder="Last Name" ></asp:TextBox>      
                    <asp:DropDownList ID="ddlClinicalType" runat="server"  DataTextField="ClinicalTypeDesc" DataValueField="ClinicalTypeID"  />
                    <asp:Button ID="btnSearch" runat="server" Text="Search"  OnClick="btnSearch_Click" />
                </div>
           
            <asp:RequiredFieldValidator 
                ID="rfvClinicalType" 
                runat="server" 
                ControlToValidate="ddlClinicalType" 
                InitialValue="" 
                ErrorMessage="Please select a Clinical option!" 
                ForeColor="Red" 
                Style="margin-left: 25px;"/>
                     <%-- </ContentTemplate>
                </asp:updatePanel>--%>
        </fieldset>
    </div>
    
    <div class="wrapperHistoricalData">
        <asp:updatePanel ID="uPanelData" runat="server"   >
                  <ContentTemplate>
                        <asp:GridView ID="gvHistoricalData" runat="server" AutoGenerateColumns="false" AllowPaging="True" AllowSorting="True" CssClass="DataEntryGridView" RowStyle-CssClass="GvGrid"  OnRowDataBound="gvHistoricalData_RowDataBound" OnRowCommand="gvHistoricalData_RowCommand">
                             <RowStyle CssClass="rowMain" />
                             <AlternatingRowStyle CssClass="rowAlt" />
                             <HeaderStyle  CssClass="rowHeader" width="100px"/>
                                       <Columns>
                                            
                                           <asp:TemplateField HeaderText="Name" ItemStyle-HorizontalAlign="Center" >
                                                 <ItemStyle CssClass="noBorder"/>
                                                    <ItemTemplate>
                                                        <asp:Label  runat="server" ID="lblName"  Text='<%# Eval("FullName") %>' CssClass="StudentName" />                                                      
                                                    </ItemTemplate>
                                          </asp:TemplateField>
                                             
                                           
                                       </Columns>
                                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                                <EditRowStyle BackColor="#999999" />
                                <FooterStyle BackColor="#5D7B9D" ForeColor="White" Font-Bold="True" />
                                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" Font-Size="15px" />
                                <PagerStyle CssClass="UserMaintUsersPager" BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                                <SortedAscendingCellStyle BackColor="#E9E7E2" />
                                <SortedAscendingHeaderStyle BackColor="#506C8C" />
                                <SortedDescendingCellStyle BackColor="#FFFDF8" />
                                <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                        </asp:GridView>
                  </ContentTemplate>
        </asp:updatePanel>

    </div>
    <div class="divInput" id="divtest">
        <div>   <--- this sint done being built yet but the information will be in here with more input boxes  ---->
            <asp:Label runat="server" ID="lbltest" Text="yeah"></asp:Label>

        </div>
    </div>

Currently when I click the row, it returns an error: "All the headers have been sent" I have left code in t=so you can see what i have tried and still cant get it to work,

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                getClinicalTypes();

            }
         
            // Restore selected row color after postback
            HighlightSelectedRow();
        }

        protected void Search(string fname, string lname, string clinicalType)
        {

           List<StudentInfo> studInfo = new List<StudentInfo>();
            if((Regex.IsMatch(fname, @"\d")) )
            {
                studInfo = CTStudentSearch.ListSearch("I", fname, "", clinicalType);
            }
            else
            {
                studInfo = CTStudentSearch.ListSearch("N", fname, lname, clinicalType);
            }
            
            gvHistoricalData.DataSource = studInfo;
            gvHistoricalData.DataBind();

        }
      
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string searchText = "";
          
            string fname = (!string.IsNullOrWhiteSpace(txtStudentFirstName.Text)) ? txtStudentFirstName.Text : "";
            string lname = (!string.IsNullOrWhiteSpace(txtStudentLastName.Text)) ? txtStudentLastName.Text : "";
            bool clinicalTypeChecked = (ddlClinicalType.SelectedIndex > 0) ? true : false;
            string clinicalType = null;
            if (clinicalTypeChecked == true)
            {
                clinicalType = ddlClinicalType.SelectedValue;

                Search(fname, lname, clinicalType);

            }
           
        }
       

        protected void gvHistoricalData_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onMouseOver", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#5D7B9D';this.style.cursor='pointer';");
                e.Row.Attributes.Add("OnMouseOut", "this.style.backgroundColor=this.originalstyle;");

                // Updated script to prevent row selection if clicking inside an input, button, or link
                //string script = "if(event.srcElement && (event.srcElement.tagName.toLowerCase() === 'input' || event.srcElement.tagName.toLowerCase() === 'button' || event.srcElement.tagName.toLowerCase() === 'a')) return;";
                //e.Row.Attributes["onclick"] = script + Page.ClientScript.GetPostBackClientHyperlink(gvHistoricalData, "Select$" + e.Row.RowIndex);

                // Add a hidden button inside the row to trigger postback
                LinkButton lb = new LinkButton();
                lb.CommandName = "Select";
                lb.CommandArgument = e.Row.RowIndex.ToString();
                lb.Style["display"] = "none"; // Hide the button
                e.Row.Cells[0].Controls.Add(lb);
                // Add OnClientClick event
                lb.OnClientClick = "return showInputDiv(); ";

                // Optionally, set a data attribute to store the row index
                lb.Attributes["data-row-index"] = e.Row.RowIndex.ToString();

                e.Row.Cells[0].Controls.Add(lb);
            }
        }
Share Improve this question edited Mar 18 at 21:48 Hamoon Hasani 33 bronze badges asked Mar 11 at 13:28 ghostflyghostfly 316 bronze badges 2
  • You have a bit too much unneeded code. You would have better chances of getting help if you would edit this to be a minimal, reproducible example - stackoverflow/help/minimal-reproducible-example – Dan Dumitru Commented Mar 11 at 13:52
  • If you want the information in "another div" just create an UpdatePanel around all the involved elements. The page does a complete load in the background anyways so for performance it does not make a difference. – VDWWD Commented Mar 12 at 11:38
Add a comment  | 

1 Answer 1

Reset to default 0

Ok, a few suggestions.

You don't need (or even want) to use the row command of the GridView.

Simple drop in a standard button into the GridView Row.

(do UseSubmitBehavior="false", as we need to use a button click, and not the browser "submit" system).

Ok, so assume this simple markup for the Gridview:

<asp:GridView ID="GridView1" runat="server"
    AutoGenerateColumns="False" DataKeyNames="ID"
    CssClass="table table-hover" style="width:50%;float:left"
    OnRowDataBound="GridView1_RowDataBound">
    <Columns>
        <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
        <asp:BoundField DataField="LastName" HeaderText="LastName" />
        <asp:BoundField DataField="City" HeaderText="City" />
        <asp:BoundField DataField="HotelName" HeaderText="HotelName" />

        <asp:TemplateField HeaderText="Description">
            <ItemTemplate>
                <asp:TextBox ID="txtDescription" runat="server"
                    TextMode="MultiLine" Rows="4" style="width:100%;border:none"
                    Text='<%# Eval("Description") %>' >
                </asp:TextBox>
                <asp:Button ID="cmdEdit" runat="server" Text="edit"
                    OnClick="cmdEdit_Click" style="display:none"
                    UseSubmitBehavior="false"
                    />
            </ItemTemplate>
        </asp:TemplateField>

    </Columns>
</asp:GridView>

And I suggest using bootstrap to style the GridView. I see you have boatloads of minor markup tweaks, and you are just wasting hours of time and work. Just use and let BoostStrap classes style the GridView for you.

And if you want alternating rows highlights, then use this:

CssClass="table table-hover table-striped"

Even MORE amazing, is that using the above bootstrap class (table and table-hover)?

Your grid will auto-resize based on the browser size.

So, to the right of the GridView, then let's assume our div with some controls that we will fill out based on a row click.

So, a wee bit of the markup looks like this:

<div id="EditRecord" runat="server" 
    style="display:none;padding:16px; float:left" clientidmode="Static"  >
    <h3>Edit Hotel</h3>
    <div style="float:left" class="iForm">
            <label>HotelName</label><asp:TextBox ID="txtHotel" 
                runat="server" f="HOtelName" width="280"></asp:TextBox> <br />
            <label>First Name</label><asp:TextBox ID="tFN" 
                runat="server" f="FirstName" Width="140"></asp:TextBox> <br />
            <label>Last Name</label><asp:TextBox ID="tLN" 
                runat="server" f="LastName" Width="140"></asp:TextBox> <br />
            <label>City</label><asp:TextBox ID="tCity" 
                runat="server" f="City" Width="140"></asp:TextBox> <br />
      .etc. etc.

Ok, so now our code behind:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        LoadData();

}

void LoadData()
{
    string strSQL =
        @"SELECT * FROM tblHotelsA
        WHERE Active = 1
        ORDER BY HotelName";

    GridView1.DataSource = General.MyRst(strSQL);
    GridView1.DataBind();
    
}


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Button cmdEdit = (Button)e.Row.FindControl("cmdEdit");
        string sJava = $@"$('#{cmdEdit.ClientID}').click();";
        e.Row.Attributes.Add("onclick", sJava);
    }
}

And then the simple standard button click code we have is thus:

protected void cmdEdit_Click(object sender, EventArgs e)
{
    Button cmdEdit = (Button)sender;
    GridViewRow gRow = (GridViewRow)cmdEdit.NamingContainer;
    int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];

    SqlCommand cmdSQL = 
        new SqlCommand("SELECT * FROM tblHotelsA WHERE ID = @ID");
    cmdSQL.Parameters.Add("@ID", SqlDbType.Int).Value = PK;

    DataRow HotelRow = General.MyRstP(cmdSQL).Rows[0];
    General.FLoader(EditRecord, HotelRow); // load up div with data

    EditRecord.Style.Add("display", "inline"); // un hide div
}

So, my Floader routine is just a re-usable routine that fills out any div with the data row we send to Floader (one fast becomes tired of typing code over and over to just set controls in a div, so with this one routine, I don't ever have to type such code over and over again - it's automatic for all divs).

So, with the above then the result is now this:

However, I tend to prefer using a jQuery.UI dialog, and thus you pop (show) the div as a dialog, and hence you wind up with a lot more screen space.

So, hence this effect I tend to prefer:

the code is really much the same. We fill out (load up) the div, but then we call the client side jQuery.UI dialog control. Hence, assuming jQuery.UI?

Then say this code:

<script>
    function popinfo(strHotelName, sRowIndex) {

        var MyDialog = $("#HotelInfo")

        strHotelName = strHotelName + " (Row index = " + sRowIndex + ")"
        MyDialog.dialog({
            title: strHotelName,
        modal: true,
        width: "940px",
        dialogClass: "dialogWithDropShadow",
        })
    }
</script>

And then the row button click code is really the same, when done loading the div, it calls the above client side routine.

Hence:

General.FLoader(HotelInfo, rHotel); // load row into controls in div HotelINfo

// call the client side pop div
// (we pass hotel name for the pop title)
string sHotelName = rHotel["HotelName"].ToString();
string sRowIndex = gRow.RowIndex.ToString();

string sJava = $@"popinfo('{sHotelName}',{sRowIndex})";

ScriptManager.RegisterStartupScript(Page, Page.GetType(), "mypop",sJava, true);

So, really similar code, with introduction of a jQuery.UI dialog.

本文标签: