How do I pass parameters to an asp.net function from an asp.net control inside an itemtemplate - asp.net

I have a vote button in a repeater and I want to use it by giving the post id which is in the same itemtemplate in a repeater/datalist. I can't pass the value I get from Eval() to the codebehind function because it takes 2 arguments which are sender and eventargs

use OnCommand instead of OnClick:
<asp:Button ID="btnVote" runat="server" Text="Vote" OnCommand="btnVote_Command" CommandArgument='<%#Eval("Column1")%>' />
In the code-behind:
protected void btnVote_Command(object sender, CommandEventArgs e)
{
object column1 = e.CommandArgument;
}

Related

How to get Postback Data on LinkButton Click Event?

I have a LinkButton in aspx page.
<asp:TextBox ID="textBoxNote" runat="server" />
<asp:LinkButton ID="linkButtonUpdateNote" Text="Update" OnClick="ButtonUpdateNoteClicked" runat="server" />
the click event handler has the following code
protected void ButtonUpdateNoteClicked(object sender, EventArgs e)
{
var note = textBoxNote.Text;
}
On Postback textBoxNote.Text is empty. I don't get the posted value. How to get the value?
It seems like you are possibly resetting the value in your Page_Load.
Check that you are using IsPostback check in the Page_Load function. see - http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx
private void Page_Load()
{
if (!IsPostBack)
{
DoThisOnce();
}
DoThisOnEachPostback();
}

Repeater in Repeater

I have a repeater inside a repeater. Where the parent repeater is bound to a Datatble which has a column with a Datatable in it.
I would like to bind the child repeater to the datatable column in the parent repeater's datarow
Is this possible? i was thinking i could do this directly in the aspx file like:
DataSource="<%# DataBinder.Eval(Container.DataItem, "Products")%>" but it doesn't seem to work.
In the parent repeater, attach a method to the OnItemDataBound event and in the method, find the nested repeater and data bind it.
Example (.aspx):
<asp:Repeater ID="ParentRepeater" runat="server" OnItemDataBound="ItemBound">
<ItemTemplate>
<!-- Repeated data -->
<asp:Repeater ID="ChildRepeater" runat="server">
<ItemTemplate>
<!-- Nested repeated data -->
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
Example (.cs):
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ParentRepeater.DataSource = ...;
ParentRepeater.DataBind();
}
}
protected void ItemBound(object sender, RepeaterItemEventArgs args)
{
if (args.Item.ItemType == ListItemType.Item || args.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater childRepeater = (Repeater)args.Item.FindControl("ChildRepeater");
childRepeater.DataSource = ...;
childRepeater.DataBind();
}
}
I would add a DataBinding event to the child repeater itself:
<asp:Repeater ID="parentRepeater" runat="server">
<asp:Repeater ID="childRepeater" runat="server"
OnDataBinding="childRepeater_DataBinding" />
</asp:Repeater>
Then just implement it:
protected void childRepeater_DataBinding(object sender, System.EventArgs e)
{
Repeater rep = (Repeater)(sender);
int someIdFromParentDataSource = (int)(Eval("ParentID"));
// Assuming you have a function call `GetSomeData` that will return
// the data you want to bind to your child repeater.
rep.DataSource = GetSomeData(int);
rep.DataBind();
}
I prefer to do it at the control level instead of the ItemDataBound level so that if you ever have to remove controls or items within your templates you don't have to worry about looking for code in the parent controls that use it. It get's all localize witht he control itself. Plus you never have to do a FindControl.
If you want to replace a control in the future you can just delete it and your code will still work since it is all self contained. Using the ItemDataBound would cause your code to still compile but crash or act unexpectedly at runtime because of it's reliance on child controls.
Here is how it's done:
DataSource='<%# ((System.Data.DataRowView)Container.DataItem)[3] %>'
So if you know the column in the parent table that holds the child table/datasource for the nested repeater you can put this directly in the aspx file.
Repeater1 OnItemDataBound event, then FindControl Repeater2. The code-behind will not find the nested Repeater2! You have to use FindControl("Repeater2").
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.DataItem != null)
{
MemberView dataRow = (MemberView)e.Item.DataItem;
var cat = MemberPresenter.getMemberID(dataRow.memID);
Repeater rp2 = (Repeater)e.Item.FindControl("Repeater2");
rp2.DataSource = cat;
rp2.DataBind();
}
}
If I need to do that, I usually do it using the ItemDataBound event of the parent repeater to bind the child repeater. If e is your EventArgs parameter, you'll have access to the child repeater via e.Item.FindControl(), and access to the data via e.Item.DataItem.
Here is an example of how to do this:
Article for nested repeater control
protected void MainRepeater_ItemDataBound(object sender, RepeaterItemEventArgs args)
{
if (args.Item.ItemType == ListItemType.Item || args.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater childRepeater = (Repeater)args.Item.FindControl("ChildRepeater");
DataTable innerTable= ((DataRowView)args.Item.DataItem)["InnerTableColumnName"] as DataTable;
childRepeater.DataSource = tasksDetails;
childRepeater.DataBind();
}
}

Template variable in ASP.NET

I have to add a Page's variable into a ItemTemplate but dont know how.
For example:
<rad:RadMenuItem ID="f" runat="server" Text="Products">
<ItemTemplate>
<div class="pitem"><%= MyText %></div>
</ItemTemplate>
</rad:RadMenuItem>
The MyText variable does exist in the context and has value but the text does not show up
Another question:
How can I add MyText to the ASP.NET page like the following?
<asp:Button Text="<%=MyText%>" .../>
I dont want to edit the code like btn.Text=MyText, just want to do that on the .aspx file as required.
Answers to second question. (Btw, you should only ask one question at a time here on Stack Overflow.)
You could use
<asp:Button Text="<%# MyText %>" />
if you call DataBind() in you code behind.
public void Page_Init(object sender, EventArgs e)
{
DataBind();
}
If the databind is expensive, I believe you could use this code, so that you only call it once, and then save the values in the ViewState.
public void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataBind();
}
}

Why won't my LinkButton inside a GridView raise its OnClick event?

I have a LinkButton inside a GridView (via an TemplateField). No matter what I try, the LinkButton will not invoke its event handler. I have tried both:
A traditional event handler ("OnClick")
A OnRowCommand event handler at the GridView level.
In both cases, I've debugged and it doesn't even catch the event handler.
If I move the LinkButton out on the page (so it's not in the GridView), it works fine, so I know the syntax is right.
Here is the "traditional" method:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Cancel" ID="DeleteButton" CausesValidation="false" OnClick="CancelThis" runat="server" />
</ItemTemplate>
<asp:TemplateField>
What's interesting is if I remove the "CancelThis" method from the code behind, it throws an error. So I know it's aware of its event handler, because it looks for it when it compiles.
Here is the RowCommand method:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Cancel" ID="DeleteButton" CausesValidation="false" CommandName="CancelThis" runat="server" />
</ItemTemplate>
<asp:TemplateField>
In this case, the GridView has:
OnRowCommand="GridView_RowCommand"
It postsback, but never hints at raising the event.
Any idea what I'm missing here?
How are you binding your GridView? Are you using a datasource control? If you are binding manually during Page_Load, it's possible that since the grid is binding every round trip, the event handler isn't catching properly. If this is the case, you may want to try something like:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//do binding
}
}
Can you post sample binding code to go with your markup?
If you really want to force the issue, you could hook into the RowDataBound event on the Grid, find the button manually and add the handler in the code behind. Something like:
markup snippet:
<asp:GridView ID="gvTest" runat="server" OnRowDataBound="gvTest_RowDataBound" />
code behind:
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
//find button in this row
LinkButton button = e.Row.FindControl("DeleteButton") as button;
if(button != null)
{
button.Click += new EventHandler("DeleteButton_Click");
}
}
}
protected void DeleteButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
// do as needed based on button.
}
I'm not sure what the purpose of the button is, but assuming it is a row delete button, you may not want to take this approach as in the event handler, you don't have direct access to the row in question, like you would using the RowCommand event.
Is there a reason you're using the Template field? Vs say a ButtonField? If you use a ButtonField, then you can hook into the RowCommand event.
markup snippet:
<asp:GridView ID="gvTest" runat="server" OnRowCommand="gvTest_RowCommand">
<columns>
<asp:buttonfield buttontype="Link" commandname="Delete" text="Delete"/>
....
</columns>
</asp:GridView>
code behind:
protected void gvTest_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "Delete")
{
//take action as needed on this row, for example
int rowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow currentRow = (sender as GridView).Rows[rowIndex];
//do something against the row...
}
}
You might want to consult MSDN docs on some of these topics:
RowCommandEvent
ButtonField class
EDIT:
To answer your question on the ButtonField - yes I don't see why you couldn't still deal with a buttonfield. Here's a snippet to find the buttonfield during row data bound and hide it (untested but I think would work...)
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//let's assume your buttonfield is in column 1
// (you'd know this based on your markup...)
DataControlFieldCell cell = e.Row.Cells[1] as DataControlFieldCell;
if(cell != null)
{
ButtonField field = cell.ContainingField as ButtonField;
//based on your criteria, show or hide the button
field.Visible = false;
//or
field.Visible = true;
}
}
}
Is viewstate turned on on your GridView? This has caught me out numerous times.
<button onclick="window.open('<%#Eval("ReportLinks")%>', '_blank');" title='<%#Eval("ReportLinks")%>'> Link</button>

asp:UpdatePanel with an ASP.NET checkbox trigger

What is the EventName property when I set up a ASP.NET checkbox control as an async postback trigger for an asp.net update panel?
I believe it is CheckedChanged.
All you have to do is set AutoPostback to true and if your CheckBox is within the UpdatePanel you shouldnt have any problems
<asp:CheckBox runat="server" ID="chk_Name" AutoPostBack="true" OnCheckedChanged="chk_Name_OnCheckedChanged"></asp:CheckBox>
Then in the OnCheckedChanged function you can do whatever you need to do
protected void chk_Name_OnCheckedChanged(object sender, EventArgs e)
{
// Do stuff here
}
OnCheckedChanged is the event name. You can autogenerate the method by double clicking the checkbox in the UI, and based on the checkbox name it will generate the method which will most likely be:
protected void CheckBox1_OnCheckedChanged(object sender, EventArgs e) {}

Resources