After deleting item List View not updating/refreshing - c#

I am using listview in Update panel. When i try to delete its deleting record from datatable but listview not updating. Bellow my button code inside in listview:
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:ListView ID="lvSelectedVoucher" OnItemCommand="lvSelectedVoucher_OnItemCommand" OnLayoutCreated="lvSelectedVoucher_LayoutCreated" runat="server">
<LayoutTemplate>
<ItemTemplate>
<tr class="odd">
<td class="text-left" colspan="2">
<div id="mvRemoveSelectedId1" class="mv-action" title="Remove item" onclick="removeVoucher">
<asp:ImageButton class="ui-icon ui-icon-close" ID="imgDelete" OnClientClick="return confirm('Are you sure you want to delete this Voucher?')"
runat="server" CommandArgument='<%# Container.DataItemIndex +1%>' CommandName="Delete" />
</div>
<asp:Literal ID="ltlMerchant" Text='<%# Eval("MerchantName") %>' runat="server" ></asp:Literal>
</td>
My server side code bellow:
protected void lvSelectedVoucher_OnItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int index = Convert.ToInt32(e.CommandArgument);
int listcount = lvSelectedVoucher.Items.Count;
if (listcount - 1 == index)
{
DataTable curTable = (DataTable)ViewState["SelectedVoucher"];
curTable.Rows[index].Delete();
ViewState.Add("SelectedVoucher", curTable);
lvSelectedVoucher.DataSource = null;
lvSelectedVoucher.DataSource = curTable;
lvSelectedVoucher.DataBind();
UpdatePanel1.Update();
}
}
}
How can I refresh my listview after delete one record ? Thanks in advance.

Something seems logically incorrect here.
Are you always deleting the last Item of ListView ? you are comparing the Index of item to be deleted with the last item actually in the two lines :
int listcount = lvSelectedVoucher.Items.Count;
if (listcount - 1 == index)
Everything else seems fine, So, did you tried deleting the Last Item of List view and see if it refreshes ?

I have using my inside ItemDeleting event & ListView refreshing properly
protected void lvSelectedVoucher_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
if (e.CommandName == "Delete")
{
int index = Convert.ToInt32(e.CommandArgument);
int listcount = lvSelectedVoucher.Items.Count;
if (listcount == index+1)
{
DataTable curTable = (DataTable)ViewState["SelectedVoucher"];
curTable.Rows[index].Delete();
ViewState.Add("SelectedVoucher", curTable);
lvSelectedVoucher.DataSource = null;
lvSelectedVoucher.DataSource = curTable;
lvSelectedVoucher.DataBind();
UpdatePanel1.Update();
}
}

Related

get selected value by drop down list in a repeater by CommandArgument of link button

I have a repeater that in it has one dropdown list and one linkbutton.
I want to get the selected value of the dropdown list by CommandArgument in linkbutton, but it just knows default value of dropdown list.
My code :
<asp:Repeater runat="server" ID="Repeater1" OnItemDataBound="Page_Load2"OnItemCommand="list_ItemCommand" >
<ItemTemplate>
<asp:DropDownList ID="dlPricelist" CssClass="width100darsad dropdownlist" runat="server" AutoPostBack="true" ViewStateMode="Enabled" >
</asp:DropDownList>
<asp:LinkButton ID="btnAddToCart" runat="server" class="btn btn-success btnAddtoCardSinglepage" CommandArgument='<%#Eval("id") %>' CommandName="addtocard">اضافه به سبد خرید</asp:LinkButton>
<asp:Label ID="xxxxxx" runat="server" Text="Label"></asp:Label>
</ItemTemplate>
</asp:Repeater>
Code behind:
protected void Page_Load2(object sender, RepeaterItemEventArgs e)
{
if (!IsPostBack)
{
string id = Request.QueryString["id"].ToString();
DataSet dsselectcategory = BLLTour.left3join(id.Trim().ToString());
var dlPricelist = (DropDownList)e.Item.FindControl("dlPricelist");
dlPricelist.DataSource = dsselectcategory.Tables[0];
dlPricelist.DataTextField = "pricelistPrice";
dlPricelist.DataValueField = "priceid";
dlPricelist.DataBind();
}
}
protected void list_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "addtocard")
{
foreach (RepeaterItem dataItem in Repeater1.Items)
{
Label xxxxxx = (Label)e.Item.FindControl("xxxxxx");
LinkButton btnAddToCart = (LinkButton)e.Item.FindControl("btnAddToCart");
xxxxxx.Text = ((DropDownList)dataItem.FindControl("dlPricelist")).SelectedItem.Text; //No error
}
}
}
I don't know how I should fix it.
You are using very old technology to show data that's not appropriate.
But if you are serious to use it, you must use FindControll method in ItemTemplate of your repeater control. You should find dropdownlist first, and then cast it to a object to be able to use it's value.

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
}
}

how add item from one listbox to another on web form

I have a two listboxes and a button. I need to add selected item from one listbox to another with click of button.
and here is the code of the button
protected void ASPxButton4_Click(object sender, EventArgs e)
{
if (listBoxSubeKiyaslama1.SelectedIndex > -1)
{
listBoxSubeKiyaslama2.Items.Add(listBoxSubeKiyaslama1.SelectedItem);
listBoxSubeKiyaslama2.Items.RemoveAt(listBoxSubeKiyaslama1.SelectedIndex);
listBoxSubeKiyaslama2.UnselectAll();
}
}
when I click the button, I see that listBoxSubeKiyaslama1.SelectedIndex is always "-1". because I think it postbacks and clears items from the first listbox. How can I fix this?
Can you try the below code:
if (listBoxSubeKiyaslama1.SelectedItem != null)
{
listBoxSubeKiyaslama2.Items.Add(listBoxSubeKiyaslama1.SelectedItem);
listBoxSubeKiyaslama2.Items.RemoveAt(listBoxSubeKiyaslama1.SelectedIndex);
listBoxSubeKiyaslama2.UnselectAll();
}
The controls will be not save the values on postbacks if EnableViewState = false. By default it is true. Please make sure you are not setting it to false.
I also suggest you to put your control in UpdatePanel to avoid full postback.
Like:
<asp:UpdatePanel ID="up1" runat="Server">
<ContentTemplate>
<asp:ListBox ID="listBoxSubeKiyaslama1" runat="server">
</asp:ListBox>
<asp:ListBox ID="listBoxSubeKiyaslama2" runat="server">
</asp:ListBox>
</ContentTemplate>
</asp:UpdatePanel>
Try the following code:-
ASPX.CS
public string GetSelectedItems(ListBox control)
{
var items = new StringBuilder();
foreach (ListItem item in control.Items)
{
if (item.Selected)
items.Append(string.Format("{0},", item.Value));
}
return items.ToString().Trim().TrimEnd(',');
}
protected void btnMoveRight_Click(object sender, EventArgs e)
{
for (int i = lbCourses1.Items.Count - 1; i >= 0; i--)
{
if (lbCourses1.Items[i].Selected == true)
{
lbCourses2.Items.Add(lbCourses1.Items[i]);
ListItem li = lbCourses1.Items[i];
lbCourses1.Items.Remove(li);
}
}
}
protected void btnMoveLeft_Click(object sender, EventArgs e)
{
for (int i = lbCourses2.Items.Count - 1; i >= 0; i--)
{
if (lbCourses2.Items[i].Selected == true)
{
lbCourses1.Items.Add(lbCourses2.Items[i]);
ListItem li = lbCourses2.Items[i];
lbCourses2.Items.Remove(li);
}
}
}
var selectedValues = GetSelectedItems(lb2);
ASPX
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div>
<asp:Label ID="lbl1" runat="server" Text="lbl1:"></asp:Label>
<asp:ListBox ID="lb1" runat="server" SelectionMode="Multiple"></asp:ListBox>
<asp:Button Runat="server" ID="btnMoveRight" Text=">>"
onclick="btnMoveRight_Click"></asp:Button>
<asp:Button Runat="server" ID="btnMoveLeft" Text="<<"
onclick="btnMoveLeft_Click"></asp:Button>
<asp:ListBox ID="lb2" runat="server" SelectionMode="Multiple"></asp:ListBox>
</div>
</ContentTemplate>
</asp:UpdatePanel>

C# delete item from listview from control outside listview

From a listview control, when checkboxes are checked and a button is clicked from outside the listview, I need to be able to delete the items that have been checked. Here's the listview:
EDIT
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) return;
var notes = (from n in db.Notes
select n).OrderBy(n => n.FiscalYear).ThenBy(n => n.Period);
notesListView.DataSource = notes;
notesListView.DataBind();
}
<asp:ListView ID="notesListView" ItemPlaceholderID="itemPlaceholder" runat="server">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<asp:CheckBox ID="checkNote" runat="server" />
<div><%# Eval("Period") %></div>
<div><%# Eval("FiscalYear") %></div>
<div><%# Eval("Account") %></div>
<div class="wrap"><%# Eval("Description") %></div>
</ItemTemplate>
<EmptyDataTemplate>
<div>No notes have been submitted.</div>
</EmptyDataTemplate>
</asp:ListView>
<br />
<asp:Button ID="deleteNotes" CssClass="deleteButton" Text="Delete Notes" runat="server" OnClick="deleteNotes_Click" />
Here's the code behind:
protected void deleteNotes_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in notesListView.Items)
{
// I know this is wrong, just not sure what to do
if (notesListView.SelectedIndex >= 0)
{
CheckBox ck = (CheckBox)item.FindControl("checkNote");
if (ck.Checked)
{
var index = item.DataItemIndex; // the item row selected by the checkbox
// db is the datacontext
db.Notes.DeleteOnSubmit(index);
db.SubmitChanges();
}
}
else
{
errorMessage.Text = "* Error: Nothing was deleted.";
}
}
}
You need to find the object before deleting it. To do so, I would add a hiddenfield to store NoteID like this:
<asp:HiddenField ID="hdnId" Value='<%#Eval("Id")%>' runat="server" />
<asp:CheckBox ID="checkNote" runat="server" />
... ... ...
And in my code I am finding the note by ID and deleting that note (You may use any other unique field instead of ID). My code may look like this:
... ... ...
int id = 0;
var hdnId = item.FindControl("hdnId") as HiddenField;
CheckBox ck = (CheckBox)item.FindControl("checkNote");
//I would check null for ck
if (ck != null && ck.Checked && hdnId != null && int.TryParse(hdnId.Value, out id)
{
// db is the datacontext
Note note = db.Notes.Single( c => c.Id== id );
db.Notes.DeleteOnSubmit(note );
db.SubmitChanges();
}

"Invalid Postback" exception on custom GridView with custom row events

I think I have figured out what happens with this program.
This is part of the markup.
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:UpdatePanel ID="upGrid" runat="server">
<ContentTemplate>
<asp:GridView ID="dgvPeliculas" runat="server" AllowPaging="true" PagerStyle-CssClass="pgr"
CssClass="mGrid" EmptyDataText="No hay más películas" OnPageIndexChanging="dgvPeliculas_PageIndexChanging1"
EnableSortingAndPagingCallbacks="true" OnRowDataBound="dgvPeliculas_RowDataBound">
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<table class="LogIn">
<tr>
<td>
<asp:UpdatePanel ID="upAlquiler" runat="server">
<ContentTemplate>
<asp:Button ID="btnAlquilar" runat="server" Text="Alquilar" CssClass="AdminButtons"
OnClick="btnAlquilar_Click" OnClientClick="javascript: Click_Alquilar(); return false" />
</ContentTemplate>
</asp:UpdatePanel>
</td>
<td>
<asp:Button ID="btnNuevo" runat="server" Text="Nuevo" CssClass="AdminButtons" OnClick="btnNuevo_Click"
OnClientClick="javascript: Click_Nuevo(); return false" />
</td>
<td>
<asp:Button ID="btnEditar" runat="server" Text="Editar" CssClass="AdminButtons" OnClick="btnEditar_Click"
OnClientClick="javascript: Click_Editar(); return false" />
</td>
<td>
<asp:Button ID="btnBorrar" runat="server" Text="Borrar" OnClientClick="javascript: Click_Borrar(); return false"
CssClass="AdminButtons" />
</td>
</tr>
</table>
I have coded it in such a way that the buttons modify it when a row is selected. The rows are selected by changing the "onclick" event (changed during the RowDataBound function), and a Javascript function.
This is how I change the code behind:
protected void dgvPeliculas_RowDataBound(object sender, GridViewRowEventArgs e)
{
dgvPeliculas.CssClass = "mGrid";
if (e.Row.RowType == DataControlRowType.DataRow)
{
string rowID = String.Empty;
rowID = "row" + e.Row.RowIndex;
e.Row.Attributes.Add("id", rowID);
e.Row.Attributes.Add("onclick", "onClick(" + "'" + rowID + "'" + ")");
e.Row.Attributes.Add("onmouseover", "this.style.cursor='pointer'; this.style.backgroundColor = '#B0C5BB';");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor = '';");
}
}
This is the JavaScript function:
/
function onClick(rowID)
{
//Si no hay ninguna seleccionada
if (selected == '') {
index = rowID;
selected = document.getElementById(rowID);
selected.onmouseover = '';
selected.onmouseout = '';
selected.style.backgroundColor = 'yellow';
}
else {
//Si se deselecciona
if (selected == document.getElementById(rowID)) {
selected.onmouseover = onmouseover;
selected.onmouseout = onmouseout;
selected.style.backgroundColor = '';
selected = '';
index = '';
}
//Deseleccionar el actual y seleccionar el nuevo
else {
selected.onmouseover = onmouseover;
selected.onmouseout = onmouseout;
selected.style.backgroundColor = '';
index = rowID;
selected = document.getElementById(rowID);
selected.onmouseover = '';
selected.onmouseout = '';
selected.style.backgroundColor = 'yellow';
}
}
}
The New button shows a ModalPopupExtender, and from there it calls a JavaScript function to validate its contents, and then does a postback to code behind to check and update the database. It also appends the register on the Grid, obviously.
The Edit button and the rest through the exception. The Edit function is particular, because its functionality is similar to that of the New button. It shows the ModalPopupExtender, goes to the JavaScript function, does the postback, to the database and updates. But this one needs to have one of the rows in the Grid selected (otherwise, there's nothing to be edited). I believe this is the reason why it throws the "Invalid Postback or Callback" exception. The same condition applies to the other buttons, and all of them throw the same exception. All, except New, which doesn't need to have a row selected.
Do you think this is the reason why I'm having this problem? And if so, how can I fix it?
Sorry if you consider this a repost of one of my previous threads, but I haven't been able to fix the problem, and I think this gives me a new clue that I can't work out neither.
Thanks.

Categories

Resources