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;
}
Related
I have a dynamic data that has to be populated on UI from .cs file.
Currently I am doing it this way:
File.aspx
<div id="divLinks" class="w3-content w3-display-container" style="max-width:100%;" runat="server">
</div>
File.aspx.cs
StringBuilder str = new StringBuilder();
str.Append("<a target=\"_blank\"><img class=\"mySlides\" src=\"" + imageLink + "\" style=\"width:100%; height:350px;\" runat=\"server\" onServerClick=\"MyFuncion_Click("+link+")\" ></a>");
divLinks.InnerHtml = str.ToString();
protected void LinkButton_Click(object sender, EventArgs e)
{
//Do something when clicked a link with parameter from that link as identifier
}
After doing this, I am not able to reach LinkButton_Click function from onServerClick.
Can someone help me with this siince I want a link with unique value to be passed to function for further processing.
You are trying to add aspnet Controls to the page as a string. That is not gonna Work. You need to add "real" Controls to the page.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
//do not add dynamic controls here
}
//create a new ImageButton instance on every page load
ImageButton ib = new ImageButton();
//set some properties
ib.CssClass = "mySlides";
ib.ImageUrl = "~/myImage.png";
//add the click method
ib.Click += LinkButton_Click;
//add the button to an existing control
PlaceHolder1.Controls.Add(ib);
}
Note that you need to add dynamic controls on every Page Load, and that includes a PostBack.
In my application i have gridview with edit button. By clicking edit button in gridview the listitem of DropDownList gets replaced by the text that is in gridview these are my dropdown list values
--select--
Roller
Heater
Aspx Code:
<asp:DropDownList ID="ddlvalue" runat="server" Width="175px" AppendDataBoundItems="true">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Roller</asp:ListItem>
<asp:ListItem>Heater</asp:ListItem>
</asp:DropDownList>
CS Code:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
ddlValue.SelectedItem.Text = (GridView1.SelectedRow.FindControl("lblValue") as Label).Text;
}
here is what you should do. you care currently changing the text of selected item instead of finding the correct item and selecting it. here is how you should do it
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string value=(GridView1.SelectedRow.FindControl("lblValue") as Label).Text;
try
{
foreach(ListItem li in ddlValue.Items)
{
if(li.Text==value)
{
li.Selected=true;
}
else
{
li.Selected=false;
}
}
}
catch
{
}
}
string value = (GridView1.SelectedRow.FindControl("lblRole") as Label).Text;
try
{
ddlvalue.ClearSelection();
ddlvalue.Items.FindByText(value).Selected = true;
}
catch
{
}
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 2 list boxes.
<asp:ListBox ID="ListBox_Region" runat="server"
DataTextField="arregion" DataValueField="arregion" AutoPostBack="True"
Height="96px"
Width="147px" DataSourceid="sqldatasource1"></asp:ListBox>
<asp:ListBox ID="ListBox_Area" runat="server"
DataTextField="ardescript" DataValueField="ardescript"
AutoPostBack="True"
OnSelectedIndexChanged="ListBox_Area_SelectedIndexChanged"
Height="96px"
Width="147px" >
So, when I select a value from ListBox_Region , the corresponding values get updated in ListBox_Area in this way:
protected void ListBox_Region_SelectedIndexChanged(object sender, EventArgs e)
{
this.ListBox_Area.Items.Clear();
string selectedRegion = ListBox_Region.SelectedValue;
var query = (from s in DBContext.areas
where s.arregion == selectedRegion
select s);
ListBox_Area.DataSource = query;
ListBox_Area.DataBind();
}
The event for ListBoxRegion_SelectedIndexChaged is written in page Load.
However, the problem is on initial page load, where the first value of ListBox_Region should be Selected by default. The second listbox should be updated to corresponding values but this should happen before selected index changed gets fired. So, can u please let me know how to do this?
Move the logic on ListBox_Region_SelectedIndexChanged to a separated method and call it from page_load when postback is false.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// Bind ListBox_Region and set the first value as selected
...
//
BindAreaList();
}
}
protected void ListBox_Region_SelectedIndexChanged(object sender, EventArgs e)
{
BindAreaList();
}
protected void BindAreaList()
{
this.ListBox_Area.Items.Clear();
string selectedRegion = ListBox_Region.SelectedValue;
var query = (from s in DBContext.areas
where s.arregion == selectedRegion
select s);
ListBox_Area.DataSource = query;
ListBox_Area.DataBind();
}
I have to set a LinkButton's OnClientClick attribute but I don't know what this value is until the LinkButton is bound to. I'm trying to set the value when the repeater binds, but I can't workout how to get the 'boundItem/dataContext' value...
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:LinkButton Text="HelloWorld" ID="Hyper1" runat="server" OnDataBinding="Repeater1_DataBinding" >
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
protected void Page_Load(object sender, EventArgs e)
{
var list = new List<TestObject>();
list.Add(new TestObject() {TestValue = "testing1"});
list.Add(new TestObject() { TestValue = "testing2" });
list.Add(new TestObject() { TestValue = "testing3" });
this.Repeater1.DataSource = list;
this.Repeater1.DataBind();
}
public void Repeater1_DataBinding(object sender, EventArgs e)
{
var link = sender as HyperLink;
//link.DataItem ???
}
Is there anyway to find out what the current rows bound item is?
Maybe you need to use ItemDataBound event. It provides RepeaterItemEventArgs argument which has DataItem available
this.Repeater1.ItemDataBound += Repeater1_ItemDataBound;
void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var dataItem = e.Item.DataItem;
}
I assume you are trying to get the value for the row that is currently being databound?
You can change your function to:
public void Repeater1_DataBinding(object sender, EventArgs e)
{
var link = sender as HyperLink;
string valueYouWant = Eval("TestValue").ToString();
// You could then assign the HyperLink control to whatever you need
link.Target = string.Format("yourpage.aspx?id={0}", valueYouWant);
}
valueYouWant now has the value of the field TestValue for the current row that is being databound. Using the DataBinding event is the best way to do this compared to the ItemDataBound because you don't have to search for a control and localize the code specifically to a control instead of a whole template.
The MSDN library had this as a sample event handler:
public void BindData(object sender, EventArgs e)
{
Literal l = (Literal) sender;
DataGridItem container = (DataGridItem) l.NamingContainer;
l.Text = ((DataRowView) container.DataItem)[column].ToString();
}
(see http://msdn.microsoft.com/en-us/library/system.web.ui.control.databinding.aspx)
As you can see it is a simple demonstration of how to access the data item and get data from it. Adapting this to your scenario is an exercise left to the reader. :)