How can I find the RepeaterItem I have clicked? - asp.net

I am creating a simple ASP page that has a Repeater control. This repeater control contains LinkButtons; so that as the repeater increases in item size, the amount of LinkButtons also increases. My question is, how can I identify uniquely the RepeaterItem to which I click the LinkButton?.
I though of using a Foreach to search through the RepeaterItems but I don't know what conditions should I use to identify the Linkbutton I cliked. By the way, each LinkButton have the same name and same ID.
My goal is to get the RepeaterItem in which that Linkbutton belongs
Thanks,
Y_Y

Assign Command/ComandArgument for your LinkButton
Assign handler 'OnCommand' for your Repeater and create event handler
In the handler you get RepeaterCommandEventArgs - use item property to access

You can use:
- Tag property of LinkButton to store object to identify the LinkButton
- Included hidden field in Repeater template to store something to identify Linkbutton.
- Using CommandArgument of LinkButton
- ...

You can look at using what is called "ItemCommand"
or you can set the CommandArgument of your LinkButton.
protected void lnkButton_Click(object sender, EventArgs e) {
LinkButton _sender = (LinkButton)sender;
string argument = _sender.CommandArgument;
}

The common solution for this scenario is to use the CommandName and/or CommandArgument properties of the button. Just bind the CommandArgument to the ID of the objects you put into the repeater. The command argument can be accessed in the click handler.

Related

gridview button field

I have a gridview with a buttonfield. I want to update a table in my database and change the button image on button click. What is best event for that where i can access the row index as well?
I have tried using the RowCommand event but cant access the row index from that event
You can try with this code - based on CommandArgument
void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Test")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = CustomersGridView.Rows[index];
}
}
Link : http://msdn.microsoft.com/fr-fr/library/system.web.ui.webcontrols.gridview.rowcommand(v=vs.80).aspx
Instead of asp:ButtonField use asp:TemplateField and an asp:Button inside that. Set a CommandName say, MyCommand. Now inside the RowCommand event, do this
var clickedRow = (GridViewRow)((Button)sender).NamingContainer;
var clickedIndex = clickedRow.RowIndex;
I've just checked the docs here http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx
If you look at the "Note" section (below for convenience) you should be able to get the RowIndex from the CommandArguement property:
Note To determine the index of the row that raised the event, use the
CommandArgument property of the event argument that is passed to the
event. The ButtonField class automatically populates the
CommandArgument property with the appropriate index value. For other
command buttons, you must manually set the CommandArgument property of
the command button. For example, you can set the CommandArgument to
<%# Container.DataItemIndex %> when the GridView control has no paging
enabled.

get selected index of databound list control on user control

I have a radiobuttonlist that lives on a user control. This user control lives in a repeater on a parent user control, and that user control lives on a page with a submit button.
So something like this:
<page>
<UserControl1>
<Repeater>
<UserControl2>
<radiobuttonlist>
</UserControl2>
</Repeater>
</UserControl1>
<Submit button />
</page>
The radiobuttonlist is dynamically populated in the code-behind of UserControl2. The problem is that when I submit the form, I need to access the SelectedValue of the radiobuttonlist, and that value is always empty. Even if I first fire the methods that populate the radiobuttonlist, the selectedvalue of the RBL is empty. I have a SelectedIndexChanged event handler on the RBL, but it never fires.
What do I need to do to be able to get the SelectedValue of the radiobuttonlist when I cause the parent page to postback?
I got it working. I guess it was an order of operations issue. The fix was to dynamically declare the event handler of the radiobuttonlist in the OnInit() of UserControl2.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
rblOptions.SelectedIndexChanged += new EventHandler(ctrlOptions_SelectedIndexChanged);
}
Once I did that, the event started firing, even though I was re-instantiating the UserControl on postback. Since the event was firing, I was able to obtain the Selected Index without needing to keep it in ViewState.
When you post your datas, you re-bind your datas so you erase your selected event or values.
Try with this code in your Page_Load (Of your User Control)
If(! IsPostBack)
{
//You build RadioButtonList
}
And persist your datas with ViewState, EnableViewState="true"

dynamic columns disappears after postback

I have a GridView with some BoundFields and two TemplateFields. In these two TemplateFields, I dynamically create UserControls containing a DropDownList and a TextBox, which users can modify.
When I try to get the values of the controls after a PostBack, the values in BoundFields are still there but my dynamic controls disappears. I can create them again but it won't get the user's values... How can I get these values before they're lost?
Here's some of my code:
In the RowDataBound event:
Select Case type
Case "BooleanBis"
e.Row.Cells(2).Controls.Clear()
Dim list1 As BooleanBisList = New BooleanBisList(avant, False)
e.Row.Cells(2).Controls.Add(list1)
e.Row.Cells(4).Controls.Clear()
Dim list2 As BooleanBisList = New BooleanBisList(apres, True)
e.Row.Cells(4).Controls.Add(list2)
Case "Boolean"
e.Row.Cells(2).Controls.Clear()
Dim list3 As BooleanList = New BooleanList(avant, False)
e.Row.Cells(2).Controls.Add(list3)
e.Row.Cells(4).Controls.Clear()
Dim list4 As BooleanList = New BooleanList(apres, True)
e.Row.Cells(4).Controls.Add(list4)
End Select
In my button click event, I try to get the user control :
Case "String"
temp.ChampValeurApres = DirectCast(Tableau1.Rows(i).Cells(selectedColumn).Controls(1), TextBox).Text
but i get the error that it doesn't exist.
You should create dynamic controls in RowCreated instead of RowDataBound because this event gets fired on every postback whereas RowDataBound only will fire when the GridView gets databound to it's DataSource.
Dynamically created controls must be recreated on every postback with the same ID as before, then they retain their values in the ViewState and events will fire correctly(f.e. a DropDownList's SelectedIndexChanged event).
So you should create them in RowCreated and "fill" them in RowDataBound(f.e. the DropDownList datasource/Items or a TextBox-Text).
I had been using:
EnableViewState="false"
in the GridView attributes. Removing it solved my problem!
I just did
protected void Page_Load(object sender, EventArgs e)
{
if (!(Page.IsPostBack))
{
// Put the selected items which u want to keep on postback
}
else
{
//regenerate auto created controls
}
}
and it worked as well

Why is DataItem always null in the Page_Load handler?

I've created an ASP.net web page with an ASP Repeater. I bind the ASP Repeater with an IOrderedEnumerable<int> DataSource.
I need to access the Repeater DataItems at inside the Page_Load event handler. However, when I try to get the value of repeater.Items[x].DataItem, I always get null. There should always be an integer value here.
In spite of this, the page otherwise renders fine. Why can't I access the DataItem property of my RepeaterItems inside the Page_Load event handler?
Your Repeater doesn't databind until later in the page lifecycle. If you want to reference Repeater.Items[i].DataItem in a Page.Load handler, try to early-bind the Repeater first:
repeater.DataBind()
Its only available during databinding.
As everyone else has said, it's only available during databinding. You will need to wire up the OnItemDataBound event of the repeater. In its event handler, you can do this:
protected void Repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
switch (e.Item.ItemType)
{
case ListItemType.Item:
case ListItemType.AlternatingItem:
WhateverType Item = e.Item.DataItem as WhateverType;
break;
}
}
The data items only exist after the databinding process has taken place. The only thing that is preserved across postbacks in the repeater are the control properties that are serialized in viewstate. If you need the data in those items, you can do like pseudocoder said and databind earlier or if that is not possible you could write a utility function that takes a repeater data item and extracts it from the controls in your repeater (assuming you stored all the information you need in those controls somehow)

How to use a UserControl inside the EditTemplate of a ListVIew?

Here is the situation:
I have a ListView showing just a list of concatenated strings obtained from different field of the objects of the datasource.
A LinkButton (with CommandName="Edit") in each row
Event handlers for OnItemDataBound and OnItemEditing
A UserControl in EditTemplate.
Now the problem is, I don't know how to use Bind expression in the UserControl. I mean, how to populate this usercontrol when the linkbutton is clicked? (I tried capturing the control in the
OnItemEditing handler. But FindControl returned null, as that handler is called before going to edit mode.)
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
TheClass theControl = (TheClass)e.Item.FindControl("theControl)";
theControl.someProperty = "bla bla bla";
}
Finally got an answer from asp.net forum. The solution is:
Modify the UserControl so that, it supports DataBinding. To do that, implement the DefaultBindingPropertyAttribute. Details here.

Resources