I am trying to do an ASP.NET application. I am using a DataSet which I set as DataSource in a ListView that I have in my .aspx file. The problem is when I click the delete button nothing seems to happen, but when I refresh the browser I get an error message as follows:
"To display the webpage again, the web browser needs to resend the
information you've previosly submitted."
I have really tried to figure out what I am doing wrong or what might cause this. This is my C# code:
namespace WebApplication1
{
public partial class _Default : Page
{
DataSet orderDetails;
protected void Page_Load(object sender, EventArgs e)
{
Message.Text = "";
string orderPath = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/orders.xml";
string orderSchemaPath = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/orderschema.xsd";
XDocument document = XDocument.Load(orderPath);
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(orderSchemaPath));
bool errors = false;
document.Validate(schemas, (o, err) =>
{
System.Diagnostics.Debug.WriteLine("Validation error: {0}", err.Message);
errors = true;
});
if (!errors)
{
System.Diagnostics.Debug.WriteLine("XML document successfully validated.");
try
{
orderDetails = new DataSet();
orderDetails.ReadXml(orderPath);
listViewOrders.DataSource = orderDetails;
listViewOrders.DataBind();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error: " + ex);
}
}
else
{
System.Diagnostics.Debug.WriteLine("XML document does not validate.");
}
System.Diagnostics.Debug.WriteLine("Page_load done");
}
void BindData()
{
listViewOrders.DataSource = orderDetails;
listViewOrders.DataBind();
}
//Call databind method in your prerender event
protected void Page_PreRender(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void OrderListView_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
listViewOrders.DeleteItem(e.Item.DataItemIndex);
BindData();
}
}
protected void OrdersListView_ItemDeleted(object sender, ListViewDeletedEventArgs e)
{
//Check if an exception occurred to display an error message.
if (e.Exception != null)
{
Message.Text = "An exception occurred deleting the contact.";
e.ExceptionHandled = true;
}
else
{
// Clear the selected index.
listViewOrders.SelectedIndex = -1;
}
}
protected void OrdersListView_OnItemDeleting(object sender, ListViewDeleteEventArgs e)
{
}
}
}
And this is the ListView that I have in my .aspx file:
<asp:ListView ID="listViewOrders"
DataKeyNames="orderid"
runat="server"
OnItemDeleting="OrdersListView_OnItemDeleting"
OnItemCommand="OrderListView_ItemCommand">
<LayoutTemplate>
<table cellpadding="2" width="640px" border="1" runat="server" id="tblProducts">
<tr runat="server">
<th runat="server">Order person</th>
<th runat="server">Order ID</th>
<th runat="server">Delete</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>
<asp:Label ID="FirstNameLabel" runat="Server" Text='<%#Eval("orderperson") %>' />
</td>
<td valign="top">
<asp:Label ID="LastNameLabel" runat="Server" Text='<%#Eval("orderid") %>' />
</td>
<td>
<asp:LinkButton ID="DeleteButton" runat="Server" class="glyphicon glyphicon-remove" CommandName="Delete" CommandArgument="X" />
</td>
</tr>
</ItemTemplate>
<EditItemTemplate>
<tr style="background-color: #ADD8E6">
<td>
<asp:LinkButton ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
<asp:LinkButton ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
</td>
<td>
<asp:TextBox ID="FirstNameTextBox" runat="server" Text='<%#Bind("orderperson") %>'
MaxLength="50" /><br />
</td>
<td>
<asp:TextBox ID="LastNameTextBox" runat="server" Text='<%#Bind("orderid") %>'
MaxLength="50" /><br />
</td>
</tr>
</EditItemTemplate>
</asp:ListView>
When you are using the listView Commands you have to update the panels.
Place your listView inside a asp:panel like this
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
... your list View Code
</ContentTemplate>
</asp:UpdatePanel>
And after the DataBind you have to update the panel by
UpdatePanel1.Update();
Related
I have a DataList control in asp.net webform, inside this DataLIst I have 2 labels that are bound to database, and one button.
One of the label represent Id and other one Stock.
I want to capture the button click event of specific product, and then add that product to the user cart.
Here is my datalist:
<asp:DataList ID="dListProduct" runat="server" RepeatColumns="4" OnItemCommand="dListProduct_ItemCommand">
<ItemTemplate>
<div>
<table class="table-responsive" border="1">
<tr>
<td>
<asp:Label runat="server" Text="Available Stock: " ></asp:Label><asp:Label ID="Label1" runat="server" Text='<%# Eval("Stock")%>'></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label runat="server" Text="Id" ></asp:Label><asp:Label ID="lblPId" runat="server" Text='<%# Eval("Product_Id")%>' Visible="false"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Button id="btnAddtoCart" runat="server" Text="Add to Cart"/>
</td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:DataList>
Here is the code I am using in OnItemCommand Event of DataList:
protected void dListProduct_ItemCommand(object source, DataListCommandEventArgs e)
{
Label lbl = (Label)e.Item.FindControl("lblPId");
Response.Write(lbl.Text);
}
but this code never get executed.
Can anyone help me out?
Copy and paste the code below exactly the way I have it.
Code behind:
public partial class DataListExample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
MyStock stock1 = new MyStock { Product_Id = 1, Stock = "Stock 1" };
MyStock stock2 = new MyStock { Product_Id = 2, Stock = "Stock 2" };
dListProduct.DataSource = new List<MyStock> { stock1, stock2 };
dListProduct.DataBind();
}
protected void dListProduct_ItemCommand(object source, DataListCommandEventArgs e)
{
Label lbl = (Label)e.Item.FindControl("lblPId");
Response.Write(lbl.Text);
}
}
public class MyStock
{
public int Product_Id { get; set; }
public string Stock { get; set; }
}
.ASPX:
<asp:DataList ID="dListProduct" runat="server" RepeatColumns="4" OnItemCommand="dListProduct_ItemCommand">
<ItemTemplate>
<div>
<table class="table-responsive" border="1">
<tr>
<td>
<asp:Label runat="server" Text="Available Stock: "></asp:Label><asp:Label ID="Label1" runat="server" Text='<%# Eval("Stock")%>'></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label runat="server" Text="Id"></asp:Label><asp:Label ID="lblPId" runat="server" Text='<%# Eval("Product_Id")%>' Visible="false"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnAddtoCart" runat="server" Text="Add to Cart" />
</td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:DataList>
Here is my DataList:
<asp:DataList ID="DataList1" runat="server" RepeatColumns="4" RepeatDirection="Horizontal"
OnSelectedIndexChanged="DataList1_SelectedIndexChanged" CommandName="Select">
<ItemTemplate>
<asp:Panel ID="Panel1" runat="server">
<table>
<tr >
<td >
<asp:ImageButton CssClass="img" ID="imgProduct" runat="server" ImageUrl='<%#Eval("StudentPics") %>'></asp:ImageButton>
</td>
</tr>
<tr >
<td >
<asp:TextBox ID="idtxt" runat="server" Text='<%# Eval("id") %>' Visible="false"></asp:TextBox>
</td>
</tr>
</table>
</asp:Panel>
</ItemTemplate>
</asp:DataList>
Here is my code:
public partial class ClassTouch4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
datalistbind();
}
}
protected void datalistbind()
{
//binding operation done !!!
}
protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
{
DataList1.SelectedItem.BackColor = Color.Red;
}
}
I am putting DataBind() in (!IsPostBack) , I tried CommandName="select" but still it is not working. I also tried other solution but selectedIndexChanged is not firing. What I am missing?
I have a repeater control. In OnItemCommand method of repeater, after doing some operations I am trying to refresh the repeater list so that it could show me the updated list. But somehow repeater list is not updated in method. However when I reload the page then repeater list gets updated with most recent items.
ASPX:
<asp:Label ID="Message1" runat="server" ForeColor="Blue" Text=""></asp:Label>
<div id="ListingAgentsData" class="panel panel-default" style="width: 920px;">
<asp:Repeater ID="rptagentList" runat="server" OnItemCommand="rptagentList_OnItemCommand">
<HeaderTemplate>
<table id="results1" cellpadding="4" cellspacing="1" width="100%">
<tr>
<td>
<strong>AgentID</strong>
</td>
<td>
<strong>Email</strong>
</td>
<td>
<strong>FullName</strong>
</td>
<td>
<strong>Driver License/Passport</strong>
</td>
<td>
<strong>Action</strong>
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lblDayofweek" runat="server" Text='<%#Eval("AgentID")%>'></asp:Label>
</td>
<td>
<asp:Label ID="lblTime" runat="server" Text='<%#Eval("Email")%>'></asp:Label>
</td>
<td>
<asp:Label ID="lblCharges" runat="server" Text='<%#Eval("FullName")%>'></asp:Label>
</td>
<td>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("DriverLicense")%>'></asp:Label>
</td>
<td>
<asp:LinkButton ID="ibtn" runat="server" Text="Approve" CommandName="Approve" CommandArgument='<%#Eval("AgentID")%>' />
<asp:LinkButton ID="LinkButton1" runat="server" Text="Reject" CommandName="Reject" CommandArgument='<%#Eval("AgentID")%>' />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
.CS:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Username"] == null)
Response.Redirect("../Login/Default.aspx");
else
{
Init();
}
}
protected void rptagentList_OnItemCommand(object source, RepeaterCommandEventArgs e)
{
try
{
if (e.CommandName == "Approve")
{
int agentId = Convert.ToInt32(e.CommandArgument);
GM gm = new GM();
if (gm.ApproveListingAgent(agentId))
{
Message1.Text = "Listing Agent with ID:"+agentId+" is approved!";
Init();
}
}
else if (e.CommandName == "Reject")
{
}
}
catch (Exception ex)
{
throw ex;
}
}
private void Init()
{
ListingAgent Agent = new ListingAgent();
DataTable dt = Agent.getPendingListingAgents();
if (dt.Rows.Count > 0)
{
rptagentList.DataSource = dt;
rptagentList.DataBind();
}
}
What am I missing?
Please help!
I have some troubles with the textbox or my brain. I can't understand what's the reason of unedittable textbox. I mean, i have listview with 3 columns:"Name","Code","Binding".
By clicking on the "Name", the first and the second column become editable. After my edit, i push button "Save"...and nothing is happened. Can't understand such a simple thing. Why it's not working?
Sorry for mistakes, i'm here for the 1st time
<asp:Content ID="ContentMain" ContentPlaceHolderID="centerContent" runat="server">
<asp:Panel ID="i_ListContainer" runat="server" HorizontalAlign="Center">
<asp:ListView ID="CpzListView" runat="server" DataKeyNames="id" InsertItemPosition="FirstItem"
OnItemCreated="i_UserLV_ItemCreated" OnItemInserted="i_UserLV_ItemInserted" OnItemEditing="i_UserLV_ItemEditing"
OnItemInserting="i_UserLV_ItemInserting" OnItemUpdated="i_UserLV_ItemUpdated"
OnItemUpdating="i_UserLV_ItemUpdating">
<LayoutTemplate>
<table cellpadding="0" cellspacing="0" class="mGrid">
<th style="width: 150px">
Name
</th>
<th style="width: 150px">
Code
</th>
<th style="width: 50px">
Binding
</th>
</thead>
<tbody>
<asp:PlaceHolder runat="server" ID="itemPlaceholder" />
</tbody>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<asp:LinkButton ID="i_viewEditLB" runat="server" CommandName="Edit" Text='<%#Bind("cpzname") %>' />
</td>
<td>
<asp:Label ID="i_viewUserFioLabel" runat="server" Text='<%#Bind("code") %>' />
</td>
<td style="text-align: center; width: 80px">
<a href='<%# GetUrl(Eval("cpzname"), Eval("code"))%>'>Bindindg</a>
</td>
</tr>
</ItemTemplate>
<InsertItemTemplate>
</InsertItemTemplate>
<EditItemTemplate>
<tr>
<td>
<asp:TextBox ID="tbCpzName" runat="server" Text='<%# Bind("cpzname") %>'></asp:TextBox>
</td>
<td>
<asp:TextBox ID="tbCpzCode" runat="server" Text='<%# Bind("code") %>'></asp:TextBox>
</td>
<td>
<asp:LinkButton ID="lbSave" runat="server" CommandName="Update" Text="Save" />
</td>
</tr>
</EditItemTemplate>
</asp:ListView>
</asp:Panel>
</asp:Content>
Here is the c# code, hope you'll help me.
namespace WebApplication2.MemberPages
{
protected void Page_Load(object sender, EventArgs e)
{
UpdateBinding();
}
private void UpdateBinding()
{
DataTable dt = AOneConnectDB.ExecuteQuery("select id, cpzname, code from cpz");
if (dt == null) return;
CpzListView.DataSource = dt;
CpzListView.DataBind();
}
protected void i_UserLV_ItemCanceling(object sender, ListViewCancelEventArgs e)
{
CpzListView.EditIndex = -1;
UpdateBinding();
}
private string GetValue(users key)
{
return CpzListView.Items.Count > 0 ? CpzListView.SelectedDataKey[key.ToString()].ToString() : string.Empty;
}
protected void i_UserLV_ItemEditing(object sender, ListViewEditEventArgs e)
{
CpzListView.EditIndex = e.NewEditIndex;
CpzListView.SelectedIndex = e.NewEditIndex;
UpdateBinding();
}
protected void i_UserLV_ItemInserted(object sender, ListViewInsertedEventArgs e)
{
// must empty
}
private string ControlValue(string controlName, ListViewItem item)
{
object c = item.FindControl(controlName);
if (c is TextBox) return (c as TextBox).Text;
if (c is CheckBox) return (c as CheckBox).Checked ? ADataBase.TRUE : ADataBase.FALSE;
if (c is DropDownList) return (c as DropDownList).SelectedValue;
return null;
}
protected void i_UserLV_ItemUpdated(object sender, ListViewUpdatedEventArgs e)
{
// must empty
}
protected void i_UserLV_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
if (CpzListView.SelectedDataKey != null && !string.IsNullOrEmpty(CpzListView.SelectedDataKey["id"].ToString()))
{
var cpzId = CpzListView.SelectedDataKey["id"];
var cpzName = ControlValue("tbCpzName", CpzListView.EditItem);
var cpzCode = ControlValue("tbCpzCode", CpzListView.EditItem);
string updateCpzQuery = string.Format(#"update cpz c
set c.cpzname = {0}
and c.code = {1}
where c.id = {2}", cpzName, cpzCode, cpzId);
if (AOneConnectDB.ExecuteNonQuery(updateCpzQuery))
{
AGUI.ShowMessage(MessageType.Success, "CPZ Modified.");
}
}
}
protected void i_UserLV_ItemCreated(object sender, ListViewItemEventArgs e)
{
// must empty
}
}
}
You should write page load method code like this:
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
return;
UpdateBinding();
}
In your code edited data lose befor editing code run, because when you click on save button first page load will execute and it bind your list view with old datas(UpdateBinding) then i_UserLV_ItemUpdating will execute. break point will help you undrestand how it work.
Nothing wrong with your code. you miss small thing.
To get data always actual you need to set EnableViewState="false". The main thing is that setting this just for specific input is not enough. This worked for me only after I set page level view state like this.
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master"
AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication8._Default"
EnableViewState="false" %>
Im trying to get values from a ListBox that has multiselection and dynamic ListItems in it. My problem is that I can't get the values once I press my "assign" button.
The idea is that I have like 10-15 listitems and they should be assigned with values. And I want to be able to select like 5 of them and press my assign button and then continue to assign other values to these items left in the list.
For som reason my ListBox.Item.Count always returns like 1 row.
Question: Is there something you need to think about when using ListBox in .NET 4.0 that isn't obvious?
Parts of the code
Front:
<fieldset>
<legend>
<asp:Label ID="Label1" runat="server"
Text="<%$ Resources:lang, ExtensionsTitleAB %>"></asp:Label>
</legend>
<div class="extLeft">
<table>
<tr>
<td>
<asp:Label ID="Label5" runat="server"
Text="<%$ Resources:lang, ExtensionsTmNumber %>"></asp:Label>
</td>
<td>
<asp:TextBox runat="server" ID="txtTmNumber"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label6" runat="server"
Text="<%$ Resources:lang, ExtensionsTmName %>"></asp:Label>
</td>
<td>
<asp:TextBox runat="server" ID="txtTmName"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label7" runat="server"
Text="<%$ Resources:lang, ExtensionsTmRegistered %>">
</asp:Label>
</td>
<td>
<asp:TextBox runat="server" ID="txtTmRegistered"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label8" runat="server"
Text="<%$ Resources:lang, ExtensionsTmLocality %>">
</asp:Label>
</td>
<td>
<asp:TextBox runat="server" ID="txtTmLocality"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label9" runat="server"
Text="<%$ Resources:lang, ExtensionsMemberShipId %>">
</asp:Label>
</td>
<td>
<asp:TextBox runat="server" ID="txtMembershipIdFaseOne">
</asp:TextBox>
</td>
</tr>
</table>
</div>
<div class="extMiddle">
<asp:Button runat="server" ID="btnAssignAB" OnClick="btnAssign_Click"
Text="<%$ Resources:lang, ButtonAssignExtensions %>" />
</div>
<div class="extRight">
<p><asp:Label ID="Label4" runat="server"
Text="<%$ Resources:lang, ExtensionsListHelp %>">
</asp:Label>
</p>
<asp:ListBox runat="server" ID="listABContainer"
SelectionMode="Multiple" AutoPostBack="false">
</asp:ListBox>
</div>
</fieldset>
The codebehind:
public partial class extensions : System.Web.UI.Page
{
private model.OrderHandling orderHandling;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["dataobject"] != null)
{
orderHandling = (OrderHandling)Session["dataobject"];
}
else
{
String url = "http://" + Request.Url.Authority + "/Default.aspx";
Response.Redirect(url);
}
if (!IsPostBack)
{
addListItems();
}
}
private void addListItems()
{
foreach (OrderLine line in orderHandling.order.getOrderLines())
{
if (line.price.getPriceType().Equals(Price_Types.SUNRISE_ONE)
|| line.price.getPriceType().Equals(Price_Types.SUNRISE_TWO))
{
listABContainer.Items.Add(
new ListItem(line.domain.domainName, line.domain.domainName));
System.Diagnostics.Debug.WriteLine("added a domain " +
"to list listABContainer : " + line.domain.domainName);
}
else if (line.price.getPriceType().Equals(Price_Types.LANDRUSH)
|| line.price.getPriceType().Equals(Price_Types.GENERAL))
{
listCDContainer.Items.Add(
new ListItem(line.domain.domainName, line.domain.domainName));
System.Diagnostics.Debug.WriteLine("added a domain " +
"to list listCDContainer : " + line.domain.domainName);
}
}
}
protected void btnAssign_Click(object sender, EventArgs e)
{
assignTMExtensions();
}
private bool assignTMExtensions()
{
bool success = true;
TradeMarkExtension tmExt = new TradeMarkExtension();
String errorMsg = "";
if (!String.IsNullOrEmpty(txtTmNumber.Text)
&&
tmExt.isValid(EXTENSION_KEYS.TM_NUMBER, txtTmNumber.Text, null))
{
tmExt.setExtension(EXTENSION_KEYS.TM_NUMBER, txtTmNumber.Text);
}
if (success)
{
System.Diagnostics.Debug.WriteLine("Succes: time for domainExtension, listCount : " + listABContainer.Items.Count);
foreach (ListItem list in listABContainer.Items)
{
if (list.Selected)
{
System.Diagnostics.Debug.WriteLine("Found a selected item " + list.Value);
try
{
OrderLine ol = orderHandling.order.getOrderLine(list.Value);
ol.domain.addExtension(tmExt);
System.Diagnostics.Debug.WriteLine("Addedd domainExtension");
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("FAILED domainExtension");
showError.Text = "An exception has occured. Please reload the page and try again.";
return false;
}
}
}
Session["dataobject"] = orderHandling;
removeListItems(listABContainer);
}
else
{
showError.Text = errorMsg;
}
return success;
}
private void removeListItems(ListBox list)
{
int i = 0;
while(i < list.Items.Count)
{
if (list.Items[i].Selected)
{
list.Items.RemoveAt(i);
}
i++;
}
}
}
Something like this?
ASPX page
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" AutoPostBack="false" />
<asp:Button ID="ButtonSubmit" runat="server" Text="Submit" OnClick="ButtonSubmit_Click" />
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataBindListBox();
}
}
protected void ButtonSubmit_Click(object sender, EventArgs e)
{
List<ListItem> selectedItems1 = ListBox1.Items.Cast<ListItem>().Where(li => li.Selected).ToList();
// or
string[] selectedItems2 = (Request.Form[ListBox1.UniqueID] ?? string.Empty).Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
}
private void DataBindListBox()
{
var data = Enumerable.Range(1, 5).Select(i => new { Text = i.ToString(), Value = i.ToString() }).ToList();
ListBox1.DataSource = data;
ListBox1.DataTextField = "Text";
ListBox1.DataValueField = "Value";
ListBox1.DataBind();
}
for one thing this seems wrong:
private void removeListItems(ListBox list)
{
int i = 0;
while(i < list.Items.Count)
{
if (list.Items[i].Selected)
{
list.Items.RemoveAt(i);
}
i++;
}
}
Don't increment i when you remove an item or you'll skip items.
Of course, that only hides the very next selected item...