im trying to create a onmouseover effect in my imagebutton which is similar to this css hover effect code below.
.button:hover
{
background-color: blue;
}
Originally I have a div tag with a class that is equals to the css hover effect and inside it is my imagebutton. When im hovering the imagebutton, the background-color blue is underneath the image. Here is the image below:
As you can see from the picture above, As i hover the Ibanez logo, it only creates a blue line at the left,right and bottom border. So i decided to try to implement the hover effect directly in imagebutton, which is surprisingly difficult than the normal css approach. I've read online that you should add onmouseover in code-behind because imagebutton doesn't normally have it and should be placed in the Page_Load.
In my case, i cannot do that because my imagebutton is inside a repeater which cannot access the image button's id directly. So i ended up making an OnItemCommand to access the imagebutton. Well unfortunately my solution did not work and no hover is happening in my imagebutton. Please help me on solving this one.
Here is the aspx:
<%# Page Title="" Language='C#' MasterPageFile='~/MasterPage.master'
AutoEventWireup='true' CodeFile='GuitarBrands.aspx.cs'
Inherits='Pages_GuitarBrands' %>
<asp:Content ID='Content1' ContentPlaceHolderID='ContentPlaceHolder1'
Runat='Server'>
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="getImageHover">
<ItemTemplate>
<div class="one-third">
<asp:ImageButton ID="brandImage" OnClick="Repeater1_OnClick"
height="250px" width="300px" runat="server" ImageUrl='<%# Eval("image")
%>' CommandArgument='<%# Eval("id") %>'
onmouseover="this.style.backgroundColor='blue';" />
</div>
</ItemTemplate>
</asp:Repeater>
</asp:Content>
Here is the aspx.cs code:
public partial class Pages_GuitarBrands : System.Web.UI.Page
{
public List<guitarBrand> brandList { get; set; }
private string brandType = "Guitar";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
DataSet ds = GetData();
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
}
protected void getImageHover(object sender,RepeaterCommandEventArgs e)
{
ImageButton image = (ImageButton)e.CommandSource;
image.Attributes.Add("onmouseover","this.style.backgroundColor=\"blue\"");
}
private DataSet GetData()
{
string CS = ConfigurationManager.ConnectionStrings["brandsConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlDataAdapter da = new SqlDataAdapter("Select * from guitarBrands", con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
protected void Repeater1_OnClick(object sender, EventArgs e)
{
ImageButton image = (ImageButton)sender;
if (image != null) {
int id = int.Parse(image.CommandArgument);
string brandName = ConnectionClassBrands.GetBrandById(id);
ConnectionClassGuitarItems.guitar = brandName;
Response.Redirect("~/Pages/GuitarItems1.aspx");
}
}
}
Try this:
protected void getImageHover(object sender,RepeaterCommandEventArgs e)
{
ImageButton image = (ImageButton)e.CommandSource;
image.Attributes.Add("class","button");
}
While in CSS, use:
<style>
.button
{
background-color: none;
}
.button:hover
{
background-color: blue;
}
</style>
Write below code in OnItemCommand event of Repeater. Hope this may help
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
ImageButton img = (ImageButton)e.Item.FindControl("brandImage");
image.Attributes.Add("onmouseover","this.style.backgroundColor=\"blue\"");
}
Related
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 the code behind the page using postback. But the postback will refresh the background color of the button I set on CSS, how should I do?
I used 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 the user press 2, the page will show page 2's details using postback and the paging number at button 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;
}
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)).
And as above shows, you are free to have other buttons and have as many post-backs as you wish - the style settings from code behind for those buttons will and should persist.
Please consider this scenario:
I have a simple page and I want to log all controls causing postback. I create this simple page. It contains a grid to show some URLs and when user click on an icon a new tab should open:
<form id="form1" runat="server">
<div>
<table style="width: 100%;">
<tr>
<td style="background-color: #b7ffbb; text-align: center;" colspan="2">
<asp:Button ID="Button3" runat="server" Text="Click Me First" Height="55px" OnClick="Button3_Click" />
</td>
</tr>
<tr>
<td style="background-color: #f1d8fe; text-align: center;" colspan="2">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" BackColor="White" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="SiteAddress" HeaderText="Address" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" ImageUrl="~/download.png" runat="server" CommandArgument='<%# Eval("SiteAddress") %>' CommandName="GoTo" Height="32px" Width="32px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
and code behind:
public partial class WebForm2 : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button3_Click(object sender, EventArgs e)
{
List<Address> Addresses = new List<Address>()
{
new Address(){ SiteAddress = "https://google.com" },
new Address(){ SiteAddress = "https://yahoo.com" },
new Address(){ SiteAddress = "https://stackoverflow.com" },
new Address(){ SiteAddress = "https://learn.microsoft.com/}" }
};
GridView1.DataSource = Addresses;
GridView1.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "MyScript", "window.open('" + e.CommandArgument.ToString() + "', '_blank')", true);
}
}
class Address
{
public string SiteAddress { get; set; }
}
every thing is fine till here. Now I create a base class for all of my pages and add below codes for finding postback control:
public class MyPageBaseClass : Page
{
protected override void OnInit(EventArgs e)
{
if (!IsPostBack)
{
}
else
{
var ControlId = GetPostBackControlName(); <------
//Log ControlId
}
base.OnInit(e);
}
private string GetPostBackControlName()
{
Control control = null;
string ctrlname = Page.Request.Params["__EVENTTARGET"];
if (ctrlname != null && ctrlname != String.Empty)
{
control = Page.FindControl(ctrlname);
}
else
{
foreach (string ctl in Page.Request.Form)
{
Control c;
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
string ctrlStr = ctl.Substring(0, ctl.Length - 2);
c = Page.FindControl(ctrlStr);
}
else
{
c = Page.FindControl(ctl);
}
if (c is System.Web.UI.WebControls.Button ||
c is System.Web.UI.WebControls.ImageButton)
{
control = c;
break;
}
}
}
if (control != null)
return control.ID;
else
return string.Empty;
}
}
and change this line:
public partial class WebForm2 : MyPageBaseClass
Now when I click on icons grid view disappears...(STRANGE...) and nothing happened. When I comment specified line then every thing will be fine...(STRANGE...).
In GetPostBackControlName nothings changed to Request but I don't know why this happened. I checked and I see if I haven't RegisterStartupScript in click event every thing is fine. Please help we to solve this problem.
Thanks
when I click on icons grid view disappears...
ASP.Net page class object instances only live long enough to serve one HTTP request, and each HTTP request rebuilds the entire page by default.
Every time you do a postback, you have a new HTTP request and therefore a new page class object instance and a completely new HTML DOM in the browser. Any work you've done for a previous instance of the page class — such as bind a list of addresses to a grid — no longer exists.
You could fix this by also rebuilding your grid code on each postback, but what I'd really do is skip the whole "RegisterStartupScript" mess and instead make the grid links open the window directly, without a postback at all.
The problem is related to OnInit event. I replaced it with OnPreLoad and every things is fine now.
For search engines: OnInit event has conflict with RegisterStartupScript
I have a gridview that shows an image as part of a column. In Edit mode, I would like to let the user upload a new image file, so I'm using the FileUpload control in the edit part of the template.
When I click on update it's showing me this:
My code:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lb = GridView1.HeaderRow.FindControl("Label1") as Label;
GridViewRow row = GridView1.Rows[e.RowIndex];
FileUpload fu = row.Cells[0].FindControl("fileupload") as FileUpload;
if (fu.HasFile)
{
string file = System.IO.Path.Combine(Server.MapPath("~/uploadedimages/"), fu.FileName);
fu.SaveAs(file);
using (Ex_RepeaterEntities entities = new Ex_RepeaterEntities())
{
Student students = (from e1 in entities.Students
where e1.Id == Convert.ToInt32(lb.Text)
select e1).First();
students.Images = file;
entities.SaveChanges();
}
}
}
After a lot of searching I found solution of above error by using this code:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int RowID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
FileUpload fileUpload = GridView1.Rows[e.RowIndex].FindControl("fileupload") as FileUpload;
if (fileUpload.HasFile)
{
fileUpload.SaveAs(Server.MapPath("~/uploadedimages/" + fileUpload.FileName));
}
}
and at page.aspx:
<asp:TemplateField HeaderText="Upload Image" SortExpression="Names">
<EditItemTemplate>
<asp:FileUpload runat="server" ID="fileupload" />
</EditItemTemplate>
<ItemTemplate>
<asp:Image ImageUrl="~/uploadedimages/1.jpg" runat="server" ID="image" />
</ItemTemplate>
</asp:TemplateField>
But a little problem here is to solve which is that file is not saving.
Finally got my own solution of above post. Here is code to be changed:
if (fileUpload.HasFile)
{
fileUpload.SaveAs(Server.MapPath("uploadedimages/" + fileUpload.FileName));
}
I am trying to get the text of my label which is inside a repeater, but I keep getting a NullPointerException.
All of the data is coming from database and it is coming correctly.
When I click on the LinkButton, I want to use the Label Text for next bit code.
Aspx page:
<asp:Repeater ID="RepeaterDepartmentParent" runat="server">
<ItemTemplate>
<div id="outerDiv" class="col-lg-3 col-xs-6" runat="server">
<!-- small box -->
<div>
<div class="inner">
<p>
<%# DataBinder.Eval(Container.DataItem, "Department_Namestr")%>
</p>
</div>
<asp:Label ID="lblDepartmentId" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Department_Idint")%>' Visible="true"></asp:Label>
<asp:LinkButton ID="linkChildDepartment" CommandName="Click" runat="server" CssClass="small-box-footer" OnClick="linkChildDepartment_Click">More info<i class="fa fa-arrow-circle-right"></i></asp:LinkButton>
</div>
</div><%--<%-- ./col -->--%>
</ItemTemplate>
</asp:Repeater>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
DataSet dsParentDepartment = null;
dsParentDepartment = objDepartmentBL.viewDepartmentparent();
RepeaterDepartmentParent.DataSource = dsParentDepartment.Tables[0];
RepeaterDepartmentParent.DataBind();
}
protected void linkChildDepartment_Click(Object sender, EventArgs e)
{
//what to write here??
//i have tried the bellow code but it gives me every data in that loop but i
//want the single data for a link button click.
//foreach (RepeaterItem item in RepeaterDepartmentParent.Items)
// {
// Label myLabel = (Label)item.FindControl("lblDepartmentId");
// myLabel.Text = Id;
//}
//edited code that works properly
LinkButton linkChildDepartment = (LinkButton)sender;
RepeaterItem item = (RepeaterItem)linkChildDepartment.NamingContainer;
Label myLabel = (Label)item.FindControl("lblDepartmentId");
}
How can I correctly reference the Link Button Label Text?
You can use the NamingContainer property to get the reference of the RepeaterItem. From there it's a short way to your label:
protected void linkChildDepartment_Click(Object sender, EventArgs e)
{
LinkButton linkChildDepartment = (LinkButton) sender;
RepeaterItem item = (RepeaterItem) linkChildDepartment.NamingContainer;
Label myLabel = (Label)item.FindControl("lblDepartmentId");
// ...
}
I am using ASP.NET, C#, Sql Server 2005 for my project and
I'm using the repeater control to form a table of users that are a member of a site and a button next to each user so that they can be added to your friends list. I have everything set up except I dont know how to get the specific info of each row after a button click. I mean,
How to send a friend request to a person whose username is displayed besides the button? or
How to access the the displayed username besides the button so that I can use it for my code?
My Script
<asp:Repeater ID="myrepeater" runat="server">
<HeaderTemplate>
<table style="font: 8pt verdana">
<tr style="background-color:#3C78C3">
<th>Search Result</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%#DataBinder.Eval(Container,"DataItem.allun")%>
<asp:Button ID="Button1" runat="server" Text="Button" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
Code Behind
protected void btnSearch_Click(object sender, EventArgs e)
{
con.Open();
if (txtSearch.Text != "")
{
SqlDataAdapter mycommand = new SqlDataAdapter("select * from WebAdminTable where allun='" + txtSearch.Text + "'", con);
DataSet ds = new DataSet();
mycommand.Fill(ds);
myrepeater.DataSource = ds;
myrepeater.DataBind();
}
else
{
//msgbox for entering value
}
con.Close();
}
protected void btnAddToMyFList_Click(object sender, EventArgs e)
{
//?
}
You can bind the userName to a label control and then you can access the value of the label control on the click of button like...
protected void btnAddToMyFList_Click(object sender, EventArgs e)
{
Button btnAddToMyFList = (Button)sender;
Label label = (Label)btnAddToMyFList.Parent.FindControl("LabelId");
String labelText = label.Text; //userName of clicked row
}