ListView ItemCommand not being reached on button click - c#

I have an aspx page using listview. The delete button I have needs to execute a sql delete using an ID found in the list view.
ASPX:
<asp:ListView runat="server" ID="ListView2" OnItemDataBound="ListView2_ItemDataBound" OnItemCommand="ListView2_ItemCommand">
<LayoutTemplate>
...
<asp:DataPager runat="server" ID="DataPager" PageSize="10" OnPreRender="DataPager_PreRender">
<Fields>
...
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
...
<td runat="server" align="right" colspan="4"><asp:Button ID="deleteRButton" CssClass="Button" runat="server" Text="Delete" CommandName="deleteRButton" OnClientClick="return confirm('You are about to delete this forum response. Are you sure you want to proceed?');" /></td>
...
</ItemTemplate>
<ItemSeparatorTemplate>
</ItemSeparatorTemplate>
</asp:ListView>
Code Behind:
protected void ListView2_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "deleteRButton") //Never makes it here with breakpoints
{
...
//Find label value and execute SQL
}
}
How do I get the button click to execute the Item Command code? I have tried using an OnClick method as well (which fires) but I don't have access to the label ID value that way.
EDIT:
Sharing page load event:
protected void Page_Load(object sender, EventArgs e)
{
GetQuestions(); //builds data table and binds to listview 1
GetAnswers(); //builds data table and binds to listview 2
questionIDBreadCrumb.Text = grabID(); //grabs id from url
//loads the current userID
getUserData();
}

SOLUTION:
Putting the page load events inside if (!ispostback) solved the issue.
if (!IsPostBack)
{
GetQuestions();
GetAnswers();
questionIDBreadCrumb.Text = grabID();
//loads the current userID
getUserData();
//validates questionOwner
}

Related

Dynamically give Id to button, Commandargument send value

Here is my part of Shop.aspx code:
<% foreach(var item in items){ %>
...
<asp:Button id="btnBuy" runat="server" class="btn" Text="Buy" OnClick ="btnBuy_Click" CommandArgument='<%#Eval("item.id") %>' />
<% } %>
I've got a loop where I create few buttons to my shopping items, and I need them to have id of my item
protected void btnBuy_Click(object sender, EventArgs e)
{
int itemId = Convert.ToInt32(btnBuy.CommandArgument);
}
On click i need to have id of the item/button clicked, to save them later in my database.
Problem -
When i click on button btnbuy.CommandArgument is "".
It's wrong: you wrote c#in asp style. You have to use a Repeater and then you can manage ItemCommand for every button click.
Aspx
<asp:Repeater ID="myRepeater" runat="server" OnItemCommand="myRepeater_ItemCommand">
<ItemTemplate>
<asp:Label id="myLbl" runat="server" Text='<%# ((Item)(Container.DataItem)).ProductName %>'/>
<asp:Button id="btnBuy" runat="server" CssClass="btn" Text="Buy" CommandName="Click" CommandArgument='<%# ((Item)(Container.DataItem)).ProductId %>' />
</ItemTemplate>
</asp:Repeater>
c# (eg. OnLoad)
List<Item> myCollection = ...; // get list of items
myRepeater.DataSource = myCollection;
myRepeater.DataBind();
...
protected void myRepeater_ItemCommand(Object sender, RepeaterCommandEventArgs e)
{
if(e.CommandName == "Click")
{
int idRecord = Convert.ToInt32(e.CommandArgument);
// do something using idRecord or
// get sender properties: ((Button)e.CommandSource).Text
}
}

Error when dropdownlist.databind() if I change from FormView.EditMode to FormView.InsertMode

I have a FormView like:
<EditItemTemplate>
<th>Test Name</td>
<td><asp:Label runat="server" ID="lblSuite" Text='<%# Eval("Suite") %>'></asp:Label></td>
</EditItemTemplate>
<InsertItemTemplate>
<th>Test Name</td>
<td><asp:DropDownList ID="insertSuite" runat="server"></asp:DropDownList></td>
</InsertItemTemplate>
Which means in InsertMode, the user can change Suite using a dropdownlist while in EditMode, the user can only see Suite but cannot do modification.
If the user click one of the record, FormView was changed into EditMode with the code:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
//getDatasource
FormView1.DataSource = objList;
FormView1.ChangeMode(FormViewMode.Edit);
FormView1.DataBind();
}
If the user click the Add New button, FormView was changed into InsertMode with the code:
FormView1.ChangeMode(FormViewMode.Insert);
protected void btnAddSingle_Click(object sender, EventArgs e)
{
FormView1.ChangeMode(FormViewMode.Insert);
DropDownList drp = (DropDownList)FormView1.FindControl("insertSuite");
drp.DataSource = otherRepo.SuiteDropdownListDataSource(2);
drp.DataTextField = "Name";
drp.DataValueField = "Name";
drp.DataBind();
}
My Problem is:
If I click the one of the record and get into EditMOde, Then click the Add New button, Then error occured.
the (DropDownList)FormView1.FindControl("insertSuite") is null.
I thought it was something about lifecycle but cannot figure it out.
You have to DataBind the FormView after you've called ChangeMode and before FormView1.FindControl.
So this works:
FormView1.ChangeMode(FormViewMode.Insert);
FormView1.DataBind();
DropDownList drp = (DropDownList)FormView1.FindControl("insertSuite");

Listview DataPager with ObjectDataSource problem

I was added the DataPager Control inside Listview. There is no problem while displaying the data. But When I click the Next page button I m getting error.
Error: The Select operation is not supported by ObjectDataSource 'ObjectDataSource2' unless the SelectMethod is specified.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
FillGrid();
}
private void FillGrid()
{
User user = new User();
user = (User)HttpContext.Current.Session["login"];
ObjectDataSource2.SelectMethod = "GetDetails";
ObjectDataSource2.SelectParameters.Add("Customer_ID", DbType.Int32, Convert.ToString(user.Customer_ID));
ObjectDataSource2.SelectParameters.Add("Selected_Period", DbType.String, Convert.ToString(Request.QueryString["period"]));
ObjectDataSource2.TypeName = "Online.Lib.Invoice";
}
CodeBeside:
<asp:ListView ID="ListView1" runat="server" DataSourceID="ObjectDataSource2">
<LayoutTemplate>
<asp:DataPager ID="DataPager1" PagedControlID="ListView1" runat="server">
<Fields>
<asp:NumericPagerField ButtonCount="10" />
<asp:NextPreviousPagerField FirstPageText="İlk" LastPageText="Son" NextPageText="İleri" PreviousPageText="Geri" />
</Fields>
</asp:DataPager>
</LayoutTemplate>
</asp:ListView>
Ok. Your FillGrid() works well and you can load it's data by the Page_Load routine. When you click "Next page" of the ListView, you're doing a PostBack.
if(!IsPostBack)
FillGrid();
}
..Which means FillGrid() aren't loaded (which is the place ObjectDataSource have it's Select instruction). That's out of what I can see in the code snippets above. Quite common to make such mistakes in IsPostBack handling.

The FormView fired event ModeChanging which wasn't handled.

Ok, so I'm struggling with using asp:formview.
I've got the formview up and running and I've added the 'Edit' button.
<asp:FormView runat="server" id="fwHotelDetails" DataKeyNames="id" OnDataBound="fwHotelDetails_DataBound" OnModeChanging="fwHotelDetails_ModeChanging" >
<ItemTemplate>
// (..) some code here which outputs some data
<asp:Repeater runat="server" id="repScore">
<ItemTemplate>
<span class="item"> Some output here</span>
<asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" />
</ItemTemplate>
</asp:Repeater>
<EditItemTemplate>
Test test, anything??
</EditItemTemplate>
</ItemTemplate>
</asp:FormView>
I've tried thefollowing solutions in the code behind - none of them works:
protected void fwHotelDetails_ItemCommand(object sender, FormViewModeEventArgs e)
{
if (e.CommandName.Equals("Edit"))
{
fwHotelDetails.ChangeMode(e.NewMode);
}
}
and this:
protected void fwHotelDetails_ModeChanging(object sender, System.Web.UI.WebControls.DetailsViewModeEventArgs e)
{
fwHotelDetails.ChangeMode((FormViewMode)e.NewMode);
}
Clicking the Edit button only gives me the following error message:
The FormView 'fwHotelDetails' fired event ModeChanging which wasn't handled
What more needs to be done?
This page is a great reference for FormView controller: http://authors.aspalliance.com/aspxtreme/sys/web/ui/webcontrols/FormViewClass.aspx
Update: I've updated code to refelct Phaedrus suggestion.
Current status is that even after clicking Edit button, the content from ItemTemplate is loaded.
You have to specify which method handles the ModeChanging event. This event is raised when a FormView control attempts to switch between edit, insert, and read-only mode, but before the mode actually changes.
<asp:FormView OnModeChanging="fwHotelDetails_ModeChanging" />
The second parameter of your method signature is 'DetailsViewModeEventArgs' it should be 'FormViewModeEventArgs'.
void fwHotelDetails_ModeChanging(Object sender, FormViewModeEventArgs e)
{
}
Just Simply write code in formview's Item_Command
protected void formview_ItemCommand(object sender, FormViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
formview.DefaultMode = FormViewMode.Edit;
formview.DataBind();
}
if (e.CommandName == "Cancel")
{
formview.DefaultMode = FormViewMode.ReadOnly;
formview.DataBind();
}
}

Strange Pager behaviour in ListView

I have a standart Page within my ListView control on the page, And the Pager is work, however in order to move to next list of items i required to click on pager link twice before it actually moves to next set of items.
The code for the pager is:
<asp:ListView ID="lv_LostCard" runat="server" DataKeyNames="request_id" EnableViewState="false">
<LayoutTemplate>
<table width="550" border="1" class="table">
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</table>
<asp:DataPager ID="lv_Books_Pager" runat="server" PageSize="10">
<Fields>
<asp:NextPreviousPagerField ShowFirstPageButton="false" ShowPreviousPageButton="true" ShowNextPageButton="false" />
<asp:NumericPagerField />
<asp:NextPreviousPagerField ShowFirstPageButton="false" ShowPreviousPageButton="false" ShowNextPageButton="true" ShowLastPageButton="false" />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
</ItemTemplate>
</asp:ListView>
and the Code behind is:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
getLostCardsList();
}
}
protected void getLostCardsList()
{
using(LostCardsManagementDataContext LostCard = new LostCardsManagementDataContext())
{
var getLostCardsList = from lc in LostCard.lostcard_request_cards
select lc;
lv_LostCard.DataSource = getLostCardsList;
lv_LostCard.DataBind();
}
Can somebody tell me what happening and how to fix it ?
Thanks in advance
I have problems with listview sincerely.
I found a solution related to your question which seems there is no other way to fix that.You need to call OnPreRender method to rebind your source to listview.
protected void listview_PreRender(object sender, EventArgs e)
{
getLostCardsList();//your method for binding
}
Be adviced, PreRender events called before your page is rendered.More clearly,if your page has a postback event will render again.That means you need to store your data into a server collection (i.e. Session).
DataBind in the PagePropertiesChanged event.
private void listview_PagePropertiesChanged(object sender, System.EventArgs e)
{
listview.DataBind();
}
Are you binding your listview in code? Make sure you are only doing that on non-postbacks.
You have turned off the viewstate on your ListView. Try it with the viewstate back on.

Categories

Resources