简体   繁体   中英

How to change color of link button after postback in asp.net

I'm new to C# and I'm running into the following issues. When I click on the link button(for pagination), it will go to code behind page using postback. But the postback will refresh the background color of button I set on css, how should I do?

I have use the ViewState but it still doesn't work.

What I originally wanted was that when the user presses the paging number, the paging number will display a different color, so that the user can tell which button they are pressing.

Like, when user press 2, the page will show page 2's details using postback and the paging number at botton will show 1 2 3 4

Here is my code,

    <asp:Repeater ID="rptPaging" runat="server" OnItemCommand="rptPaging_ItemCommand" >  
                                                <ItemTemplate>  
                                                    <asp:LinkButton ID="lnkPage"
                                                        Style="padding: 8px; margin: 2px; background: lightgray; border: solid 1px #666;font-weight: bold;" 
                                                        CommandName="Page" CommandArgument="<%# Container.DataItem %>" runat="server" CssClass="listbtn" 
                                                        ForeColor="Black" Font-Bold="True"><%# Container.DataItem %>  
                                                    </asp:LinkButton>  
                                                </ItemTemplate>  
                                            </asp:Repeater>  

this is the code behind,

 public int PageNumber
    {
        get
        {
            if (ViewState["PageNumber"] != null)
            {
                return Convert.ToInt32(ViewState["PageNumber"]);
            }
            else
            {
                return 0;
            }
            
    }
        
        set { ViewState["PageNumber"] = value; }
    }
    private int iPageSize = 100;

    private void BindRepeater(DataTable dt)
    {

  
        //Finally, set the datasource of the repeater
        PagedDataSource pdsData = new PagedDataSource();
        DataView dv = new DataView(dt);
        pdsData.DataSource = dv;
        pdsData.AllowPaging = true;
        pdsData.PageSize = iPageSize;
        if (ViewState["PageNumber"] != null)
            pdsData.CurrentPageIndex = Convert.ToInt32(ViewState["PageNumber"]);
        else
            pdsData.CurrentPageIndex = 0;
        if (pdsData.PageCount > 1)
        {
            rptPaging.Visible = true;
            ArrayList alPages = new ArrayList();
            for (int i = 1; i <= pdsData.PageCount; i++)
                alPages.Add((i).ToString());
                 

            rptPaging.DataSource = alPages;
            rptPaging.DataBind();
        }
        else
        {
            rptPaging.Visible = false;
        }


        rptTxnHist.DataSource = pdsData;
        rptTxnHist.DataBind();
    }
protected void rptPaging_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
    {
        string sDateFr = datepicker.Value;
        string sDateTo = datepicker2.Value;
        PageNumber = Convert.ToInt32(e.CommandArgument) - 1;
        //ViewState["PageNumber"] = Convert.ToInt32(e.CommandArgument);
   
        LoadUI(PageNumber, "NAME", sDateFr, sDateTo);
    }

css code:

a:hover, a:focus{
color:white;
background-color:black;
}

I recommends to see this W3 solutions before struggling more. I know Microsoft control are easy to use but hard to implement interactively but some modification will give ease of work. Try session variable if you want more control on page appearance behavior.

Well, in "most" cases, if you drop in and want a data pager, then the highlight of the given "selected" page option should occur 100% automatic for you.

In other words, if one "can" get the css to do this for you?

You REALLY want that choice (css) to work for you.

If you "can/do" get this to work, then you not really have to write much code at all for the pager to work.

Also, you don't note or mention what you trying to page?

Are you trying to page a GridView, ListView, repeater of data?

You can quite much page any of the above, and once you get your pager working you can quite much re-use that pager over and over. (makes for a consistent look and feel throughout your applcation).

so, say we want to page a Grid View.

So, our pager style can be this:

        <style>
            .GridPager a, .GridPager span
            {
                display: block;
                height: 20px;
                width: 15px;
                font-weight: bold;
                text-align: center;
                text-decoration: none;
                margin-right:8px;
            }
            .GridPager a
            {
                background-color: #f5f5f5;
                color: #969696;
                border: 1px solid #969696;
            }
            .GridPager span
            {
                background-color: #A1DCF2;
                color: #000;
                border: 1px solid #3AC0F2;
            }
    </style>

And our GridView can be this:

So we set AllowPaging = true, and set the pager style

        <asp:GridView ID="GHotels" runat="server" CssClass="table table-hover" AutoGenerateColumns="false"
            width="45%" DataKeyNames="ID" AllowPaging="True" 
            OnPageIndexChanging="GHotels_PageIndexChanging" PageSize="6"   >
            <Columns>
                <asp:BoundField DataField="FirstName" HeaderText="FirstName"  />
                <asp:BoundField DataField="LastName" HeaderText="LastName"    />
                <asp:BoundField DataField="HotelName" HeaderText="Hotel Name"    />
                <asp:BoundField DataField="Description" HeaderText="Description" ItemStyle-Width="270" />                
            </Columns>
            <PagerStyle CssClass="GridPager" />
        </asp:GridView>

Our code to load now is this:

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

    void LoadData()
    {
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            string strSQL = 
                @"SELECT * FROM tblHotels 
                  WHERE Description is not null 
                  ORDER BY HotelName";
            using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
            {
                DataTable rstData = new DataTable();
                conn.Open();
                rstData.Load(cmdSQL.ExecuteReader());
                GHotels.DataSource = rstData;
                GHotels.DataBind();
            }
        }
    }


    protected void GHotels_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GHotels.PageIndex = e.NewPageIndex;
        LoadData();

    }

And we now get/see this:

在此处输入图像描述

Now, say a ListView - it supports a pager, and thus say this:

        <asp:ListView ID="ListView1" runat="server"  Allowpaging="true" >
            <ItemTemplate   >
                <tr>
                    <td><asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' /></td>                        
                    <td><asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' /></td>
                    <td><asp:Label ID="HotelNameLabel" runat="server" Text='<%# Eval("HotelName") %>' /></td>
                    <td><asp:Label ID="CityNameLabel" runat="server" Text='<%# Eval("City") %>' /></td>
                    <td><asp:Label ID="ProvinceLabel" runat="server" Text='<%# Eval("Province") %>' /></td>
                </tr>
            </ItemTemplate>
            <LayoutTemplate>
                <table id="itemPlaceholderContainer" runat="server" border="0" class="table table-hover">
                    <tr runat="server" >
                        <th runat="server">FirstName</th>
                        <th runat="server">LastName</th>
                        <th runat="server">HotelName</th>
                        <th runat="server">City</th>
                        <th runat="server">Province</th>
                    </tr>
                    <tr id="itemPlaceholder" runat="server" >
                    </tr>
                </table>
            </LayoutTemplate>
        </asp:ListView>

And right below, we can drop in a pager, and not really use a style sheet, but the existing bootstrap classes - say like this:

<div id="pagging" runat="server">
    <asp:DataPager ID="DataPager1" runat="server" PagedControlID="ListView1" PageSize="9" >
        <Fields>
            <asp:NextPreviousPagerField NextPageText=" Next <i class='fa fa-chevron-left'></i> " 
                ShowNextPageButton="true"
                ShowPreviousPageButton="false" ShowFirstPageButton="false"
                ButtonCssClass="btn btn-default" RenderNonBreakingSpacesBetweenControls="false" RenderDisabledButtonsAsLabels="false" />

            <asp:NumericPagerField ButtonType="Link" 
                CurrentPageLabelCssClass="btn btn-primary disabled" 
                RenderNonBreakingSpacesBetweenControls="false"
                NumericButtonCssClass="btn btn-default" ButtonCount="10" 
                NextPageText="..." NextPreviousButtonCssClass="btn btn-default" />
            <asp:NextPreviousPagerField PreviousPageText=" <i class='fa fa-chevron-right'></i> Prev" 
                ShowPreviousPageButton="true"
                ShowNextPageButton="false" ShowLastPageButton="false"
                ButtonCssClass="btn btn-default" RenderNonBreakingSpacesBetweenControls="false" RenderDisabledButtonsAsLabels="false" />
        </Fields>
    </asp:DataPager>
<br />
</div>

And now I get/see this:

在此处输入图像描述

AGAIN I did NOT have to write any code to figure out the "highlight" of the button.

This suggests that you are perhaps re-binding the grid on page load each time.

EVERY one of my web pages has code in the FIRST page load to setup/load/do stuff to load drop downs, grids etc. And that code needs to run ONLY on the REAL first page load.

That means your first REAL page load is to fire ONLY one time. So, every page needs this code stub in page load event to load things (we check for.IsPostBack - that's te REAL first page load).

Hence this:

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

So, once you set this up, then really all your efforts are on formatting the pager - not writing code to "highlight" one of the pager buttons - that should "just work" for you. (but if you re-load on page load each time, often such formatting and settings will get messed up - so, you don't as a general rule want your setup + data load code to run EACH time on page load (hence the.IsPostBack code stub).

And maybe I kind of like those round fuzzy balls for the buttons.

So, with this format:

<style>
    .GridPager a, .GridPager span {
        display: block;
        height: 22px;
        width: 28px;
        text-align: center;
        margin-right: 12px;
        box-shadow: 4px 4px 4px 0px gray;
        border-radius: 10px;
    }

    .GridPager a {
        background-color: #ddd5d5;
        border: 1px solid #969696;
        margin-right: 12px;
        box-shadow: 4px 4px 4px 0px gray;
        border-radius: 10px;
    }

        .GridPager a:hover {
            background-color: #789eca;
            transition: 0.5s;
        }

    .GridPager span {
        background-color: #808080;
        color: #000;
        border: 1px solid #3AC0F2;
    }
</style>

And say a GridView, then I get/see this:

在此处输入图像描述

My point?

Once you get the style working, you should NOT be writing code behind to manage which button is to stay highlighed - it should just work.

I'll post a specific working example, but you don't mention if you trying to "page" a Grid, repeater, or whatever.

Now, I read the question to be about a data pager.

But, the goal seems to be just to change the style of a button in the repeater once clicked.

So, assume this repeater:

    <style>
        .mylinkbtn {
            padding: 8px;
            margin: 2px; 
            background: lightgray; 
            border: solid 1px #666;
            font-weight: bold;
        }
    </style>

    <div style="padding:35px;width:25%">

    <asp:Repeater ID="rptPaging" runat="server"  >  
    <ItemTemplate>  
        <div style="text-align:right">

        <asp:Label ID="lblH" runat="server" Font-Size="14"
            Text= "View Hotel Name ">
        </asp:Label>

        <asp:Label ID="lblHotel" runat="server" Font-Size="14"
            Text='<%# Eval("HotelName") %>' >
        </asp:Label>

        <asp:LinkButton ID="lnkPage"  CssClass="mylinkbtn"
            runat="server" Text="View"
            ForeColor="Black" Font-Bold="True"
            OnClick="lnkPage_Click"  > 
        </asp:LinkButton>  

        <br />
        <br />

        </div>
    </ItemTemplate>  
</asp:Repeater> 

This code to load:

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


    void LoadData()
    {
        DataTable rstOptions =
            MyRst("SELECT ID, HotelName FROM tblHotelsA ORDER BY HotelName");

        rptPaging.DataSource = rstOptions;
        rptPaging.DataBind();

    }

    DataTable MyRst(string strSQL)
    {
        DataTable rstData = new DataTable();
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
            {
                cmdSQL.Connection.Open();
                rstData.Load(cmdSQL.ExecuteReader());
            }
        }
        return rstData;
    }

REMEMBER.,.! - ONLY re-bind the grid ONE time (!IsPostBack). If you leave that bit out, then you are re-binding the repeater and will LOSE your button change of style.

But, a simple post-back WILL NOT re-set the style(s) to apply to any repeated control(s) in the repeater.

So, we get this:

在此处输入图像描述

Now, our button click code. I really DO NOT LIKE the command and button event model for a gridview, listview, repeater etc.

I just drop in a plane jane button, or whatever. Just in the markup type in onclick= (and then space bar - you are promped to create a event click for that button (or any other event). That way you don't have to mess around with row command.

Hence this code:

    protected void lnkPage_Click(object sender, EventArgs e)
    {
        LinkButton btn = (LinkButton)sender;
        RepeaterItem rRow = (RepeaterItem)btn.NamingContainer;

        int MyRowIndex = rRow.ItemIndex;
        Debug.Print("row index = " + MyRowIndex);
        // get hotel name value
        Label lblHotel = (Label)rRow.FindControl("lblHotel");
        Debug.Print("Row click hotel = " + lblHotel.Text);

        // change button class to show it was clicked 
        btn.CssClass = "btn btn-info";
    }

So, for each button I click on, we see this:

在此处输入图像描述

And the output window of the clicks shows this:

在此处输入图像描述

So any style you apply to controls - including that link button will work, and CAN survive a post-back. But, your standard page load event NEAR ALWAYS has to be placed inside of a.IsPostBack stub (last 100+ web pages have such a code stub), In other words, if you re-bind the repeater, then yes of course it will re-plot, re-load. and you lose the style buttons or any other style you applied.

However, since your page,IsPostBack stub on runs on the REAL first page load. then such style settings for buttons controls etc, will persist. and they have automatic view state preserved for you.

So, either you not setting the style to the given row in the repeater, or your page load event is re-binding and re-loading the repeater which of course will blow out and re-set your buttons.

But, for Gridview, repeater, Listview and more such data bound controls? The state of such controls and buttons should persist, assuming you use the all important,IsPostBack code stub (which as I noted. quite much every single page you write will need if you loading up any data bound control(s)).

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