find control inside datalist on page load - c#

I want to find an item in the datalist on page load method this is my code
protected void Page_Load(object sender, EventArgs e)
{
//some code here
for (int i = 0; i < count ; i++)
{
LinkButton LinkButton6 = (LinkButton)sender;
DataListItem item = (DataListItem)LinkButton6.NamingContainer;
LinkButton lnkbtn6 = (LinkButton)DataList1.Items[item.ItemIndex].FindControl("LinkButton6");
}
}
but this error appears to me :Unable to cast object of type 'ASP.default2_aspx' to type 'System.Web.UI.WebControls.LinkButton'.

Page_Load is not an event triggered by LinkButton so sender cannot be a LinkButton. It is a Page event. Use OnItemDataBound instead
Markup
<asp:DataList OnItemDataBound="DataList1_OnItemDataBound" runat="server" ID="MdataList">
<ItemTemplate>
<asp:LinkButton runat="server" ID="LinkButton6" Text="Text"></asp:LinkButton>
</ItemTemplate>
</asp:DataList>
Codebehind
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DataList1_OnItemDataBound(object sender, DataListItemEventArgs e)
{
LinkButton lnkBtn6 = (LinkButton)e.Item.FindControl("LinkButton6");
lnkBtn6.Text = "Some Text Here";
}

On this line:
LinkButton LinkButton6 = (LinkButton)sender;
the sender object is the Page, not LinkButton, isn't it?

Related

How to change button text on page load based on listview value on Visual Studio

I want to change my button text on page load after retrieving the list view values.
For example,
<asp:Label ID="favouriteLabel" runat="server" Text='<%# Eval("favourite") %>' />
If this label value is 1, the button will change to Favourited.
I have retrieved the list view values by binding the listview
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Label activity = (Label)e.Item.FindControl("favouriteLabel");
activityID = activity.Text;
}
}
then, I get the activityID and do a simple if-else check on the page load
protected void Page_Load(object sender, EventArgs e)
{
if (activityID == "1")
{
Button4.Text = "Favourited";
}
else
{
Button4.Text = "Favourite";
}
}
However it does not work. Anybody?
Do that inside a PostBack check in the load event, for instance:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (activityID == "1")
{
Button4.Text = "Favourited";
}
else
{
Button4.Text = "Favourite";
}
}
}
Read more about postback here
Page_Load happens before your ItemDataBound event so the activityId you are looking at in the Page_Load will never be 1.
Just put the code you have in the Page_Load into the ItemDataBoundEvent

Why does an ASP.NET TextBox.TextChanged not fire when the new text is blank?

I have a somewhat complicated setup for an ASP.NET TextBox. It is inside of a user control that's inside a repeater that's inside a repeater.
I am able to load text into the TextBox and also get TextChanged to fire when text is changed to anything EXCEPT FOR blank/empty. The event doesn't fire when the user clears out the TextBox.
Does anyone know why ASP.NET might discriminate between text and blank?
I made a simplified version of my problem to separate it from possible other factors. I get the same results.
Below is my aspx markup:
<div>
<asp:Repeater runat="server" ID="rptRepeat" EnableViewState="False">
<ItemTemplate>
<asp:repeater runat="server" ID="rptChild" EnableViewState="False">
<ItemTemplate>
<uc:Things runat="server" ID="ucChild"></uc:Things>
</ItemTemplate>
</asp:repeater>
</ItemTemplate>
</asp:Repeater>
</div>
<asp:Button runat="server" ID="btnBtn" Text="click"/>
Below is my user control markup
<asp:TextBox runat="server" ID="txtText"></asp:TextBox>
Below is the aspx code behind
private List<List<TestObj>> data = null;
protected void Page_Init(object sender, EventArgs e)
{
this.rptRepeat.ItemCreated += rptRepeat_ItemCreated;
this.rptRepeat.ItemDataBound += rptRepeat_ItemDataBound;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
Session["data"] = data = new List<List<TestObj>>();
for (var x = 0; x < 5; x++)
{
data.Add(new List<TestObj>());
for (var y = 0; y < 5; y++)
{
data[0].Add(new TestObj
{
Text = x + "_" + y
});
}
}
}
else
{
data = (List<List<TestObj>>)Session["data"];
}
this.rptRepeat.DataSource = data;
this.rptRepeat.DataBind();
}
void rptRepeat_ItemCreated(object sender, RepeaterItemEventArgs e)
{
var rptChild = (Repeater)e.Item.FindControl("rptChild");
rptChild.ItemDataBound += rptChild_ItemDataBound;
}
void rptRepeat_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var rptChild = (Repeater)e.Item.FindControl("rptChild");
var rowObj = (List<TestObj>)e.Item.DataItem;
rptChild.DataSource = rowObj;
rptChild.DataBind();
}
void rptChild_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var ucChild = (WebUserControl1)e.Item.FindControl("ucChild");
var rowObj = (TestObj)e.Item.DataItem;
ucChild.data = rowObj;
}
Below is the user control code behind
public TestObj data = null;
protected void Page_Init(object sender, EventArgs e)
{
this.txtText.TextChanged += txtText_TextChanged;
}
protected void Page_PreRender(object sender, EventArgs e)
{
this.txtText.Text = data.Text;
}
void txtText_TextChanged(object sender, EventArgs e)
{
data.Text = this.txtText.Text;
}
You can download the whole project at https://www.dropbox.com/s/p6zkqqsw71fvuyw/textchangetest.zip?dl=0 if you want to try tinkering with stuff to get me an answer.
The databinding of the repeater was intentionally put in Page_Load because otherwise child controls' events don't fire.

How to retrieve value from dynamic button

I created a dynamic button inside c# code and I have assigned some value in button.text but the problem is that on buttn_Click event I want to show details related to that value. So any idea how to do this?
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < list.Count; i++)
{
lnk1 = new Button();
VW obj1 = list[i];
lnk1.Text = " "+obj1.ticketNo+": "+obj1.subject+": "+obj1.qu;
lnk1.Click += new EventHandler(lnk1_Click);
}
}
I want to show above mentioned obj1.ticketno in next page like ticket No: some value is selected
You could retrieve the reference to the button using the sender parameter of the event handler and cast the value to the Button type.
In lnk1_Click event handler you can get the link by type casting the sender to Button type and get the link text. Using that you can retrieve ticket number for which click has been done.
Something like this:
void lnk1_Click(object sender)
{
Button clickedLinkButton = sender as Button;
String buttonText = clickedLinkButton .Text;
String clickedTicketNumber =
buttonText
.SubString(0, buttonText.IndexOf(':'))
.Trim();"
}
Here is the sample code segment
protected void lnk1_Click(object sender, EventArgs e)
{
Button bt = sender as Button;
bt.Text;
}
you can use GridView or Repeater and in Iteme Template you can put button. and bind perticular grid or repeater.
<asp:repeater runat="server" id="rpt">
</ItemTemplate>
<asp:LinkButton runat="serevr" ID="lbtnLInkButton" CommandArgument='<%#Eval("ID") %>' CommandName="Edit" OnClick="lbtnLInkButton_Click">"+<%#Eval("ticketNo")%> <%#Eval("subject")%> <%#Eval("qu")%>
</ItemTemplate>
</asp:repeater>
Bind This Repeater to Datatable or make Dummy DataTable and bind it.
DataTable dt = new DataTable();
dt.Columns.Add("ticketNo");
dt.Columns.Add("Subject");
dt.Columns.Add("qu");
for (int i = 0; i < list.Count; i++)
{
dt.Rows.Add(new object[] { "Ticket Number Value", "Subject Value", "qu Value"});
}
rpt.DataSource = dt;
rpt.DAtabind();
You can get button event like this
protected void lbtnLInkButton_Click(object sender, EventArgs e)
{
int i = Convert.ToInt32(((LinkButton)sender).CommandArgument);
}
***Note : I have writtern the code extempore and not rested it on Visual Studio so there May be Some Spelling Mistakes.**

Asp.net: Page won't refresh after clicking dynamically generated Button controls

Clicking on any of the dynamically generated button controls does indeed call the b_Click method and delete the given user, however, upon deleting the page does not reload the 'new' list of users.
protected void Page_Load(object sender, EventArgs e)
{
DbDB db = new DbDB();
List<User> users = db.GetUsers().ExecuteTypedList<User>();
foreach (User u in users)
{
Button b = new Button();
b.Text = u.FirstName;
b.Click += new EventHandler(b_Click);
PlaceHolder1.Controls.Add(b);
}
}
}
void b_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
DbDB.User.Delete(x => x.FirstName == b.Text);
}
protected void Page_Load(object sender, EventArgs e) {
LoadUsers();
}
void b_Click(object sender, EventArgs e) {
Button button = (Button)sender;
string firstName = button.CommandArgument;
DbDB.User.Delete(x => x.FirstName == firstName);
PlaceHolder1.Controls.Remove(button);
}
void LoadUsers() {
DbDB db = new DbDB();
List<User> users = db.GetUsers().ExecuteTypedList<User>();
foreach (User user in Users) {
Button button = new Button();
button.CommandArgument = user.FirstName; // normally the user "id" to identify the user.
button.Text = user.FirstName;
button.Click += new EventHandler(b_Click);
PlaceHolder1.Controls.Add(button);
}
}
That's because the Page_Load event is called before the Click event so when you're retrieving the list of users from the database in Page_Load the user is still in there. As a quick solution you could move the code from Page_Load to PreRender event.
Have a look at this link for more info on the page life cycle: http://msdn.microsoft.com/en-us/library/ms178472.aspx
You don't need to select users with every post-back. Also you don't need to create controls at runtime for this.
Following is an alternative way.
<asp:Repeater runat="server" ID="myRepeater">
<ItemTemplate>
<asp:Button runat="server" OnClick="Button_Click" Text='<%# DataBinder.Eval(Container.DataItem, "FirstName") %>' />
</ItemTemplate>
</asp:Repeater>
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// load users
myRepeater.DataSource = users;
myRepeater.DataBind();
}
}
protected void Button_Click(object sender, EventArgs e)
{
// delete user
Button button = sender as Button;
button.Visible = false;
}
Write your page_load body inside
if(!IsPostBack)
{
....
}
That should work.

Connect HyperLinkField click to Server-side method (c#)

I have a HyperLinkField which I populate with the urls from a datatable, the field in the datatable is called EncodedAbsUrl.
However, I want to connect this link to a code behind method instead
What I do now
var encodedAbsUrl = new string[] { "EncodedAbsUrl" };
var hf = new HyperLinkField
{
HeaderText = "Link",
DataTextField = "ServerUrl",
DataNavigateUrlFields = encodedAbsUrl,
DataNavigateUrlFormatString = "{0}",
Target = "_blank",
};
But id like to do something like this
var encodedAbsUrl = new string[] { "EncodedAbsUrl" };
var hf = new HyperLinkField
{
HeaderText = "Link",
DataTextField = "ServerUrl",
NavigateUrl = clicker(encodedAbsUrl["{0}"]),
Target = "_blank",
};
protected void clicker(string url)
{
//...
}
Well you can see my attempts are unsuccessful :)
Any advice is appreciated
Thanks!
if you will use HyperLinkField so you will not need to Clicker or any postback event because this field will be rendered as <a> tag. I made a sample example using HyperLink control and LinkButton control that will be postback your page.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gv.DataSource = [YourDataSource];
gv.DataBind();
}
}
protected void Clicker(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Link")
{
Response.Redirect(e.CommandArgument.ToString());
}
}
protected void gv_DataBinding(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hlink = e.Row.FindControl("hlink") as HyperLink;
hlink.NavigateUrl = ((Person)e.Row.DataItem).NavUrl;
hlink.Text = ((Person)e.Row.DataItem).NavUrl;
hlink.Target = "_blank";
LinkButton lnkButton = e.Row.FindControl("lnkButton") as LinkButton;
lnkButton.Text = ((Person)e.Row.DataItem).NavUrl;
lnkButton.CommandName = "Link";
lnkButton.CommandArgument = ((Person)e.Row.DataItem).NavUrl;
}
}
you GridView will like this
<asp:GridView runat="server" ID="gv" OnRowCommand="Clicker" OnRowDataBound="gv_DataBinding"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat="server" ID="hlink"></asp:HyperLink>
<asp:LinkButton runat="server" ID="lnkButton"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You'll need to use a LinkButton if you want to be able to postback to the server in the way you require.
This class has an OnClick event unlike the HyperLinkField you've been using.
You can find out more info about the LinkButton class here.

Categories