I created some ImageButtons in code-behind.
Then, populated a list of ImageButtons as:
protected void Image_Click(object sender, ImageClickEventArgs e)
{
ImageButton imgButton = sender as ImageButton;
imgButton.ImageUrl = Resource.TICK_IMAGE;
// some work
ImageButtonList.Add(imgButton);
}
On my ASPX page some images will appear now.
After some time, I want to remove those images.
I tried something like:
buttonList.Clear();
But, still the images are appearing on the ASPX page. How should I remove those images?
My whole code looks like:
public static List<Image> RandomImages = new List<Image>();
protected void Page_Load(object sender, EventArgs e)
{
buttonList.Clear();
if (!string.IsNullOrEmpty(Request.Form[Resource.RESET_BUTTON_ID]) || !Page.IsPostBack)
{
RandomImages = ResetGame();
}
AddCardsToDisplay(RandomImages, CardDiv, true);
}
public void AddCardsToDisplay(List<Image> Images, System.Web.UI.HtmlControls.HtmlGenericControl DivisionName, bool isClickable)
{
foreach (var image in Images)
{
ImageButton button = Utilities.CreateImageButton(image.NewImageURL, image.ID, CardDiv);
AddImageButtonClickEvent(button, isClickable);
}
}
protected List<Image> ResetGame()
{
NumberOfClicks = 0;
return GetRandomImages(NUMBER_OF_IMAGES);
}
public static ImageButton CreateImageButton(string imageUrl, string id, System.Web.UI.HtmlControls.HtmlGenericControl DivisionName)
{
ImageButton button = new ImageButton { ImageUrl = imageUrl, ID = id };
DivisionName.Controls.Add(button);
return button;
}
Just use the command "Clear" from your list. To empty the usages pf those buttons. Do that instead of your foreach loop
ImageButtonList.Clear();
And it should work. :-)
EDIT
I thought that the imagelist was the parent of those controls. But it does not seem to be the case.
If you want to remove the button itself, try do something as:
imgButton.Parent.Controls.Remove(imgButton);
If you want to just hide them. Then do
imgButton.Visible = false;
Last but not least. You can reset the image url, set it to null. And it shouldmt be visible (not sure if it will give you a red x though)
Related
After a long time searching for this problem I've decided to try my luck here... I'm trying to add a tooltip (title) for the items in a Drop Down List.The title is showed in IE and Firefox browsers. The DDL is creating dynamically and the DDL's DataSource is a list called "labCourses" .This is my code:
protected void Page_Load(object sender, EventArgs e)
{
ExpScheduleClass ExpSC = new ExpScheduleClass();
List<string> labCourses = ExpSC.getCourseList();
// dynamically create a dropdown list (aka DDL)
DDLCourses = new DropDownList();
DDLCourses.DataSource = labCourses; // set the data source
DDLCourses.DataBind(); // bind the data to the DDL control
BindTooltip(DDLCourses);
DDLCourses.AutoPostBack = true;
DDLCourses.SelectedIndexChanged += DDLCourses_SelectedIndexChanged;
coursePH.Controls.Add(DDLCourses);
}
public void BindTooltip(ListControl lc)
{
for (int i = 0; i < lc.Items.Count; i++)
{
lc.Items[i].Attributes.Add("title", lc.Items[i].Text);
}
}
I looked at the option element with the web inspector and the title was there (in the html), but is does not shown when the mouse was over the option.
In other browsers the title is shown on mouse hover. What may be the cause for this? Thank you very much...
I get this error:
System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name:index.
Same code was running perfectly in windows form app, but in asp.net i see this error.
My code is here:
public partial class Timeline : System.Web.UI.Page
{
TwitterService servis;
ListBox tweetid = new ListBox();
protected void Page_Load(object sender, EventArgs e)
{
servis = new TwitterService(consumer key,secret,token,token);
tweetid.Items.Clear();
ListBox2.Items.Clear();
IEnumerable<TwitterStatus> anasayfa = servis.ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions { Count = 200 });
var gelen = servis.ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions { Count = 200, MaxId = anasayfa.Last().Id });
foreach (var tweet in gelen)
{
tweetid.Items.Add(tweet.Id.ToString());
ListBox2.Items.Add(tweet.Text);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
servis.Retweet(new RetweetOptions() { Id = long.Parse(tweetid.Items[ListBox2.SelectedIndex].ToString())});
String uyarı = "alert('Retweetlendi!');";
ClientScript.RegisterOnSubmitStatement(this.GetType(), "ConfirmSubmit", uyarı);
}
}
The problem here is that you have two ListBoxes, one (tweetid) storing the id's (presumably a key of sorts) of the tweets, and the other (ListBox2) storing the text of the tweets. You also don't seem to be adding the dynamically created tweetid ListBox to the page anywhere (and presumably the intention is that the tweetid ListBox is hidden or similar).
You are then attempting to store synchronize the selected text drop down back to the original tweetid in the code behind Button click handler, based on the relative indexes of the data - it is apparant that the two listboxes are getting out of synch, plus, you aren't validating the user has selected a valid item, hence the ArgumentOutOfRange exception.
Although in theory this could be made to work, e.g. by ensuring that the data isn't lost in each page_load roundtrip as per #Dan's answer, and also by enabling ViewState, this all seems rather fragile to me.
I would propose that instead, you use a single ListBox and use the DataTextField to show the tweet to the user, and the DataValueField to track the Id of each tweet:
.aspx
<asp:ListBox runat="server" ID="TweetsListBox" DataTextField="Text" DataValueField="Id" EnableViewState="True" />
.aspx.cs Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Replace with your code to fetch tweets here
TweetsListBox.DataSource = FetchSomeTweets();
// We've alread set the names of the properties to use `Id` and `Text` in the aspx
TweetsListBox.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
long tweetIdToRetweet;
if (long.TryParse(TweetsListBox.SelectedValue, out tweetIdToRetweet))
{
servis.Retweet(new RetweetOptions() { Id = tweetIdToRetweet });
}
else
{
// Display Error that user must select a tweet
}
}
For test purposes, I used the following mock models for your tweet service:
class Tweet
{
public int Id { get; set; }
public string Text { get; set; }
}
private static readonly IEnumerable<Tweet> SomeTweets = new[]
{
new Tweet { Id = 123, Text = "This is tweet 123" },
new Tweet { Id = 234, Text = "This is tweet 234" },
new Tweet { Id = 345, Text = "This is tweet 345" }
};
Your Page_Load method is populating the ListBox everytime the page postback, even before your button click event.
Thus, ListBox2.SelectedIndex will not be the the index that the user selected, since it is freshly populated in the Page_Load method.
You should add a postback check on your page_load and only populate the ListBox if the request is not a postback.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
servis = new TwitterService(consumer key,secret,token,token);
tweetid.Items.Clear();
ListBox2.Items.Clear();
IEnumerable<TwitterStatus> anasayfa = servis.ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions { Count = 200 });
var gelen = servis.ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions { Count = 200, MaxId = anasayfa.Last().Id });
foreach (var tweet in gelen)
{
tweetid.Items.Add(tweet.Id.ToString());
ListBox2.Items.Add(tweet.Text);
}
}
}
I have two ASP.NET Grid views, which contain an Image-button, which both call an Edit On-click event. the On-click event looks like:
protected void Edit(object sender, EventArgs e)
{
ImageButton ibtn1 = sender as ImageButton;
using (GridViewRow row = (GridViewRow)((ImageButton)sender).Parent.Parent)
{
txtMessageID.ReadOnly = true;
txtMessageID.Text = row.Cells[2].Text;
txtReference.Text = row.Cells[6].Text;
buttonClicked.Text = ibtn1.ID.ToString();
popup.Show();
}
}
which sole purpose is to fire off a ModalDialogBox, with key items from the grid view being clicked. My problem is that one of the grids doesn't have the Cells[6] (Reference) and therefore falls over. What i need to do is wrap a statement around this cell checking which grid (ID) the button click came from.
I'm not using Row-command, as this wouldn't allow for a single method call from multiple grids. My question is how do I obtain the Grid ID from the Image Button being clicked within this method (see above)?
ended up using the RowCommand of the Gridview, and then used the following to get what i need:
rotected void Edit(object sender, GridViewCommandEventArgs e)
{
ImageButton ibtn1 = sender as ImageButton;
GridView grd = sender as GridView;
string gridName = grd.ClientID;
string buttonId = e.CommandName;
using (GridViewRow row = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer)
{
txtMessageID.ReadOnly = true;
txtMessageID.Text = row.Cells[2].Text;
if (gridName == "grdMessageDups")
{
txtReference.Text = row.Cells[6].Text;
}
buttonClicked.Text = ibtn1.ID.ToString();
popup.Show();
}
}
I have a field that currently changes text on a mouse click. This field is on multiple pages of my report, but clicking it only changes the text for that page. Here is my code for that:
const string sShowDetail2 = "Show Cumulative";
const string sHideDetail2 = "Hide Cumulative";
ArrayList expandedValues2 = new ArrayList();
// This function returns a value indicating whether a certain
// category's details should be expanded.
bool ShouldShowDetail2(int CategoryID)
{
return expandedValues2.Contains(CategoryID);
}
private void lbShowHide2_BeforePrint(object sender, PrintEventArgs e)
{
XRLabel label = (XRLabel)sender;
if (ShouldShowDetail2((int)label.Tag))
{
label.Text = sHideDetail2;
}
else
{
label.Text = sShowDetail2;
}
}
private void lbShowHide2_PreviewClick(object sender, PreviewMouseEventArgs e)
{
// Obtain the category's ID stored in the label's Tag property.
int index = (int)e.Brick.Value;
// Determine whether the current category's details are shown.
bool showDetail2 = ShouldShowDetail2(index);
// Toggle the visibility of the category's details.
if (showDetail2)
{
expandedValues2.Remove(index);
}
else
{
expandedValues2.Add(index);
}
Now I have another field that I need to simply toggle all instances of the field(every page) on click. I do not need it to read the tag of the particular one I clicked because it will be changing all of them at the same time. My problem is that I don't know how to get them all to change on mouse click. How could I modify the code above to change all instances of the label?
Here is something you could try
private void ChangeXRLabels(Control control)
{
foreach(Control childControl in control.Controls)
{
XRLabel label = childControl as XRLabel;
if(label != string.Empty)
label.Text = "Your Text Value goes Here";
else if(childControl.Controls.Count > 0)
ChangeXRLabels(childControl);
}
}
I have the following code:
<asp:BulletedList ID="filingList" runat="server" DisplayMode="LinkButton"
onclick="filingList_Click">
</asp:BulletedList>
<asp:Literal ID="filingLiteral" runat="server"></asp:Literal>
and in the backend I fill the bulleted list with ListItems (where AlternateFileUrl is a url string that points to text formatted in html):
foreach (ShortFiling file in filingArray)
{
filingList.Items.Add(new ListItem(file.Type.ToString() + " "
+ file.Date.ToString(), file.AlternateHtmlFileUrl));
}
How do I access the text of the value of the item that's clicked on in the filingList then set it to the asp:Literal control? Here is the empty event handler that I defined and assume that I need to put the code in to set the asp:literal to the value of the specified ListItem.
protected void filingList_Click(object sender, BulletedListEventArgs e)
{
//put code here to set the asp:Literal text to
//the value of the item that is clicked on
}
protected void filingList_Click(object sender, BulletedListEventArgs e)
{
var value = filingList.Items[e.Index].Value;
filingLiteral.Text = value;
}
UPDATE 2
Ok you want the text from that URL, keep your markup as it was and change the code behind to this:
protected void filingList_Click(object sender, BulletedListEventArgs e)
{
var value = filingList.Items[e.Index].Value;
using(var client = new WebClient())
{
string downloadString = client.DownloadString(value);
filingLiteral.Text = downloadString;
}
}
You will need to add the System.Net namespace.
If I have understood your question correctly, you would just handle the click event of the BulletedList control, like:
protected void filingList_Click(object sender, BulletedListEventArgs e)
{
BulletedList bull = (BulletedList)sender;
ListItem li = bull.Items(e.Index);
filingLiteral.Text = li.Value;
}