Can't edit textbox on the listview - c#

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" %>

Related

Deleting item from ListView

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();

Datalist selectIndex Change event not firing

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?

Repeater list is not getting updated in OnItemCommand method

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!

check value of checkboxes inside listview

I have a ListView with a checkbox field inside that gets the id set dynamically.
I also have a button that when pressed needs to check if any of the checboxes have been checked but I'm not sure how to get this done.
Any idea on how I can get this done?
Thanks
This is my code:
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id"
DataSourceID="EntityDataSource1" EnableModelValidation="True">
<ItemTemplate>
<tr>
<td class="firstcol">
<input id='Checkbox<%# Eval("Id") %>' type="checkbox" />
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<th width="50" scope="col" class="firstcol">
</th>
</tr>
<tr ID="itemPlaceholder" runat="server"></tr>
</table>
<asp:Button ID="btnDownload" runat="server" Text="Download" Height="26px"
onclick="btnDownload_Click" />
</LayoutTemplate>
</asp:ListView>
protected void btnDownload_Click(object sender, EventArgs e)
{
???????
}
disclaimer: I'm more of a back-end/wpf developer. There are likely more elegant solutions, but this seems to work.
Change your checkbox id so it is not unique (sorry, this will break w3c validation) and set it to runat server and set the value of the CheckBox to your data source's Id:
<ItemTemplate>
<tr>
<td class="firstcol">
<label runat="server"><%# Eval( "Id" ) %></label>
<input id="MyCheckBox" value='<%# Eval("Id") %>'
type="checkbox" runat="server" />
</td>
</tr>
</ItemTemplate>
You can then iterate through the ListView's items collection and find the CheckBoxes:
protected void btnDownload_Click( object sender, EventArgs e )
{
foreach( ListViewDataItem item in ListView1.Items )
{
var chk = item.FindControl( "MyCheckBox" ) as System.Web.UI.HtmlControls.HtmlInputCheckBox;
if( chk != null && chk.Checked )
{
string value = chk.Value;
}
}
}
If you wanted a bit of Linq:
protected void btnDownload_Click( object sender, EventArgs e )
{
var checkedCheckBoxes = ListView1.Items.Select( x => x.FindControl( "MyCheckBox" ) as HtmlInputCheckBox )
.Where( x => x != null && x.Checked );
// do stuff with checkedCheckBoxes
}

Get Data Value From ListView ItemDataBound

I'm sure I've done this before but really cant remember how.
In the ItemDataBound event of a ListView I need to get the actual data value. I cant seem to find it in the ListViewItemEventArgs object that gets passed in.
Thanks
Use the ListViewDataItem in the ItemDataBound event:
protected void yourListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
if (e.Item.ItemType == ListViewItemType.DataItem)
{
YourDataSource yourDataSource= (YourDataSource )dataItem.DataItem;
}
}
I think what you're after is the ListViewDataItem.DataItem
protected void Score_ItemDataBound(object sender, Telerik.Web.UI.RadListViewItemEventArgs e)
{
if (e.Item is RadListViewItem)
{
RadListViewDataItem item = e.Item as RadListViewDataItem;
object dataItem = ((System.Data.DataRowView)(((RadListViewDataItem)e.Item).DataItem)).Row.ItemArray[2].ToString();
string raetest = Convert.ToString(dataItem);
}
}
<asp:ListView ID="ContactsListView"
DataSourceID="ContactsDataSource"
ConvertEmptyStringToNull="true"
OnItemDataBound="ContactsListView_ItemDataBound"
runat="server">
<LayoutTemplate>
<table cellpadding="2" width="680px" border="0">
<tr style="background-color: #ADD8E6" runat="server">
<th runat="server">First Name</th>
<th runat="server">Last Name</th>
<th runat="server">E-mail Address</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
<asp:DataPager runat="server" ID="PeopleDataPager" PageSize="12">
<Fields>
<asp:NumericPagerField ButtonCount="10" />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<tr style="background-color: #CAEEFF" runat="server">
<td>
<asp:Label ID="FirstNameLabel" runat="server" Text='<%#Eval("FirstName") %>' />
</td>
<td>
<asp:Label ID="LastNameLabel" runat="server" Text='<%#Eval("LastName") %>' />
</td>
<td>
<asp:Label ID="EmailAddressLabel" runat="server" Text='<%#Eval("EmailAddress") %>' />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
Server side
protected void ContactsListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
// Display the e-mail address in italics.
Label EmailAddressLabel = (Label)e.Item.FindControl("EmailAddressLabel");
// EmailAddressLabel.Font.Italic = true;
string valueoftheControl = EmailAddressLabel.Text;
/* you have to get the value like this.
If its a dropdown or any other use their
corresponding property to get the value.*/
}
}

Categories

Resources