I am working with the .Net List view along with a data pager to enable pagination for a list view.
I am able to set the pagination working perfectly for the list view but I wish to have a method being called when ever the user clicks on any of the page numbers in the data pager.
I want to perform some operation whenever the page number is called. I guess there is no onclick event, so is there any other way by which this is possible.
Thanks
you can set it as imagebutton or linkbutton.
I have piece of code.. you just need to implement it.
you can set link and click event.
foreach (DataPagerFieldItem dpfItem in dtpPaging.Controls)
{
foreach (Control cPagerControls in dpfItem.Controls)
{
if (cPagerControls is ImageButton)
{
ImageButton imgNavigation = cPagerControls as ImageButton;
imgNavigation.PostBackUrl = CommonLogic.GetFormattedURL(strPageUrl);
imgNavigation.Click += new ImageClickEventHandler(imgNavigation_Click);
}
if (cPagerControls is LinkButton)
{
LinkButton lnkNumbers = cPagerControls as LinkButton;
lnkNumbers.PostBackUrl = CommonLogic.GetFormattedURL(strPageUrl);
lnkNumbers.Click += new EventHandler(lnkNumbers_Click);
}
}
}
You can bind a handler to the OnPagePropertiesChanging Event of the List View. A PagePropertiesChangingEventArgs object is passed to the handler as argument which contains MaximumRows and StartRowIndex properties. You can use these to calculate the current page number. It is very easy and requires no code-behind event binding as the solution proposed by sikender.
Related
I
have created 2 drop down list and 2 text boxes dynamically in asp.net .i disable text box at run time .i want that when i select item from drop down text box should be enable how to perform this task please help me :(
On SelectedIndexChanged on the dropDownList call a function that sets the textbox enabled = true. To access controls that have been dynamically added you can use FindControl as per C#, FindControl
I think something like this should help you:
In your page's OnInit event:
DropDownList ddl = new DropDownList();
ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
placeholder.Controls.Add(ddl); //assuming this is what you use to dynamically show the dropdown list
TextBox yourTextbox = new TextBox(); //declare the variable outside to be able to be accessed by other methods, but it must be instantiated here. declaration here is for illustration purposes only
yourTextBox.Enabled = false;
placeholder.Controls.Add(yourTextBox);
Inside the instantiated event handler:
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
yourTextbox.Enabled = true;
}
I have a checkboxlist control that I need to check the values of when a Submit button is clicked by the user onscreen(C#).
This checkboxlist is part of a user control that I am referencing within my page markup.
However, when I check the values of the checkboxlist within the code of the submit button, all of the values are gone (i.e it says there are no items at all in the checkboxlist control).
Anyone know why this would be happening? I am doing the exact same thing in code in another place with another checkboxlist user control and it works perfectly.
I don't have my exact code to hand but below is a simplified version of what I am doing.
Basically I am binding data to the Checkboxlist only when it is NOT a postback on the usedr control.
USER CONTROL WHICH CONTAINS ONLY THE CHECKBOXLIST CONTROL Page_Load()
If(!IsPostBack)
{
foreach(var item in myVals)
{
ListItem i = new ListItem();
i.Text = item.Text;
i.Value = item.Value;
i.Selected = false;
myCheckBoxListControl.Add(i);
}
}
Now I have a submit button function which checks the values in the checkboxlist...
SubmitButton_Click()
{
foreach(ListItem item in myCheckBoxListControl.Items)
{
// process each one here. The code never gets in here as there are never any items in the checkboxlist
}
}
Anyone know why the CheckboxList has lost all of its items by the time the submit button function gets executed? The checkboxlist has EnableViewState set to true.
I have a GridView with dynamically created image buttons that should fire command events when clicked. The event handling basically works, except for the very first time a button is clicked. Then, the postback is processed, but the event is not fired.
I have tried to debug this, and it seems to me, that the code executed before and after the first click is exactly the same as for any other clicks. (With the exception that in the first click, the event handler is not called.)
There is some peculiarity in that: The buttons which fire the event are created dynamically through databinding, i.e. databinding must be carried out twice in the page lifecycle: Once on load, in order to make the buttons exist (otherwise, events could not be handled at all), and once before rendering in order to display the new data after the events have been processed.
I have read these posts but they wouldn't match my situation:
ASP.NET LinkButton OnClick Event Is Not Working On Home Page,
LinkButton not firing on production server,
ASP.NET Click() event doesn't fire on second postback
To the details:
The GridView contains image buttons in each row. The images of the buttons are databound. The rows are generated by GridView.DataBind(). To achieve this, I have used the TemplateField with a custom ItemTemplate implementation. The ItemTemplate's InstantiateIn method creates the ImageButton and assigns it the according event handler. Further, the image's DataBinding event is assigned a handler that retrieves the appropriate image based on the respective row's data.
The GridView is placed on a UserControl. The UserControl defines the event handlers for the GridView's events. The code roughly looks as follows:
private DataTable dataTable = new DataTable();
protected SPGridView grid;
protected override void OnLoad(EventArgs e)
{
DoDataBind(); // Creates the grid. This is essential in order for postback events to work.
}
protected override void Render(HtmlTextWriter writer)
{
DoDataBind();
base.Render(writer); // Renews the grid according to the latest changes
}
void ReadButton_Command(object sender, CommandEventArgs e)
{
ImageButton button = (ImageButton)sender;
GridViewRow viewRow = (GridViewRow)button.NamingContainer;
int rowIndex = viewRow.RowIndex;
// rowIndex is used to identify the row in which the button was clicked,
// since the control.ID is equal for all rows.
// [... some code to process the event ...]
}
private void DoDataBind()
{
// [... Some code to fill the dataTable ...]
grid.AutoGenerateColumns = false;
grid.Columns.Clear();
TemplateField templateField = new TemplateField();
templateField.HeaderText = "";
templateField.ItemTemplate = new MyItemTemplate(new CommandEventHandler(ReadButton_Command));
grid.Columns.Add(templateField);
grid.DataSource = this.dataTable.DefaultView;
grid.DataBind();
}
private class MyItemTemplate : ITemplate
{
private CommandEventHandler commandEventHandler;
public MyItemTemplate(CommandEventHandler commandEventHandler)
{
this.commandEventHandler = commandEventHandler;
}
public void InstantiateIn(Control container)
{
ImageButton imageButton = new ImageButton();
imageButton.ID = "btnRead";
imageButton.Command += commandEventHandler;
imageButton.DataBinding += new EventHandler(imageButton_DataBinding);
container.Controls.Add(imageButton);
}
void imageButton_DataBinding(object sender, EventArgs e)
{
// Code to get image URL
}
}
Just to repeat: At each lifecycle, first the OnLoad is executed, which generates the Grid with the ImageButtons. Then, the events are processed. Since the buttons are there, the events usually work. Afterwards, Render is called, which generates the Grid from scratch based upon the new data. This always works, except for the very first time the user clicks on an image button, although I have asserted that the grid and image buttons are also generated when the page is sent to the user for the first time.
Hope that someone can help me understand this or tell me a better solution for my situation.
A couple problems here. Number one, there is no IsPostBack check, which means you're databinding on every load... this is bound to cause some problems, including events not firing. Second, you are calling DoDataBind() twice on every load because you're calling it in OnLoad and Render. Why?
Bind the data ONCE... and then again in reaction to events (if needed).
Other issue... don't bind events to ImageButton in the template fields. This is generally not going to work. Use the ItemCommand event and CommandName/CommandArgument values.
Finally... one last question for you... have you done a comparison (windiff or other tool) on the HTML rendered by the entire page on the first load, and then subsequent loads? Are they EXACTLY the same? Or is there a slight difference... in a control name or PostBack reference?
Well I think the event dispatching happens after page load. In this case, its going to try to run against the controls created by your first data-binding attempt. This controls will have different IDs than when they are recreated later. I'd guess ASP.NET is trying to map the incoming events to a control, not finding a control, and then thats it.
I recommend taking captures of what is in the actual post.
ASP.NET is pretty crummy when it comes to event binding and dynamically created controls. Have fun.
Since in my opinion this is a partial answer, I re-post it this way:
If I use normal Buttons instead of ImageButtons (in the exact same place, i.e. still using MyItemTemplate but instantiating Button instead of ImageButton in "InstantiateIn", it works fine.
If I assert that DoDataBind() is always executed twice before sending the content to the client, it works fine with ImageButtons.
Still puzzled, but whatever...
I have a page that dynamic create a table of contacts, if the contact got an email I also create an image button with a click event.I have a similar function in the rest of the page that works perfectly. And I used this before without any problems:
protected void CreateContactsList(IQueryable<AA_BranschFinder.Login.vyWebKontaktpersoner> lContacts) // Creates a table in the aspx from an IQueryable List
{
if (1 == 1)
{
htmlTblContactsContent.Rows.Clear();
foreach (var p in lContacts)
{
HtmlTableRow tr = new HtmlTableRow();
HtmlTableCell tdName = new HtmlTableCell();
HtmlTableCell tdCompanyName = new HtmlTableCell();
HtmlTableCell tdEmailAdress = new HtmlTableCell();
tdName.InnerHtml = p.strFnamn + " " + p.strEnamn;
tdCompanyName.InnerHtml = p.strNamn;
//Displays an image if the contacts has an email
if (p.strEpost != null)
{
ImageButton imgEmail = new ImageButton();
imgEmail.CommandArgument = p.intKundID.ToString();
imgEmail.ImageUrl = "images/symbol_letter.gif";
imgEmail.CssClass = "letter";
imgEmail.Click +=new ImageClickEventHandler(imgEmail_Click);
tdEmailAdress.Controls.Add(imgEmail);
}
tr.Cells.Add(tdCompanyName);
tr.Cells.Add(tdEmailAdress);
tr.Cells.Add(tdName);
htmlTblContactsContent.Rows.Add(tr);
}
}
}
void imgEmail_Click(object sender, ImageClickEventArgs e)
{
Breakpoint here
throw new NotImplementedException();
}
The page is living inside a java popup window. But I have paging numbers with similar event creation that works fine. But they are Linkbuttons.
Where are you calling your Create method? You need to do it before the other event handlers run, ideally in the Page.Init. Otherwise, the data posted back to the page are indicated an event firing for a control that doesn't yet exist.
I would also make sure that you give your ImageButton an ID. It will make debugging a lot easier.
imgEmail.ID = String.Format("EmailImageButton_{0}", p.intKundID);
An alternative solution is to look at the __eventtarget and __eventargument parameters in the Request object and see which button was clicked there.
You'll have to create the dynamic controls on EVERY postback. Also check the code in the imgEmail_Click event handler; if you have created the event handler method using .NET IDE's Alt + Shift + F10 method, then there's a chance that you have not removed this line -
throw new Exception("The method or operation is not implemented.");
If I´m not misstaking the imagebutton is a submit kind of button while the linkbutton is an a-tag with javascript. Maybe changing your imagebutton click (ie usesubmitbehaviour set to false) will solve your problem.
Make sure the event handler is added on your postbacks. When adding it just on initial page load, the event won't be handled! (Just encountered and solved this problem myself.)
This is probably a simple question but I am not an ASP.NET developer and I am quite stuck.
I have a simple search routine that returns between zero and several hundred results. Each of these must be added to the page as a button and I want to set the text of the button and the CommandArgument property so that when the button is clicked I can read the CommandArgument back and react accordingly.
However, when I click the button the event does not run at all. How can I get it to run?
The code for building the button list (simplified for readability) is as follows:
foreach (SearchResult sr in searchResults)
{
Button result = new Button();
result.Text = sr.name;
result.CommandArgument = sr.ID.ToString();
AccountSearchResults.Controls.Add(result);
result.Click += new EventHandler(SearchResultClicked);
AccountSearchResults.Controls.Add(new LiteralControl("<br/>"));
}
At the minute to test, I have popped a label on the form to put the CommandArgument in. This code is never executed though.
void SearchResultClicked(object sender, EventArgs e)
{
Label1.Text = ((Button)sender).CommandArgument;
}
You mentioned in another answer that you are adding these when a button is clicked. Looking at your code, I would suggest that you try setting a unique ID for each button added, then ensure that on loading the page that buttons with the same IDs and CommandArgument values are reloaded. When a dynamically loaded button is clicked, it must still exist on the page after postback for the event to fire.
I think the ID is all you need, plus your requirement for the CommandArgument). You could put the ID information in the ViewState if you can't get it repeat without a long search process.
Where are you adding this buttons?
if you are adding them inside another control then the event might be raising in the parent control. This happens on DataRepeaters and DataGrids for example.
I think you need to use the OnCommand event handler, rather than the OnClick i.e. try changing this:
result.Click += new EventHandler(SearchResultClicked);
to this:
result.Command += new EventHandler(SearchResultClicked);
UPDATE
Try changing the type of second argument to your event hander from EventArgs to CommandEventArgs. You might also have to set the CommandName property on your button i.e.
result.CommandName = "foo";