c#.NET ListBox with dynamic data and multiselection problem - c#

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

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

How to capture button click event from asp.net DataList

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>

Checkbox state not changed on postback

I have the following mark up for a User Control (.ascx)
<table>
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="Select Logical Symbol to Search:"></asp:Label>
</td>
<td>
<asp:DropDownList ID="ddlComponentType" runat="server"
onselectedindexchanged="ddlComponentType_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td>
<asp:CheckBox ID="chkAdvSearchAllLibs" runat="server" ToolTip="Check this box to search all available libraries" Text="Search All Libraries"/>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label2" runat="server" Text="Search by Logical Symbol Properties:"></asp:Label>
</td>
<td>
</td>
</tr>
On page Load
protected void Page_Load(object sender, EventArgs e)
{
SearchResults(ref attributeSearch, compTypeID);
}
where SearchResults is
private void SearchResults(ref string attributeSearch, int compTypeID)
{
DataTable dtResults = this.AdvancedSearchControl.GetSearchResults(ref attributeSearch, compTypeID);
}
And in my UserControl.ascx.cs
public DataTable GetSearchResults(ref string _attrVals, int compTypeID)
{
//Other Logic Goes Here
IEnumerable<Model.ComponentInfo.ComponentType> compTypeResult = from compTypes in BLLibrary.GetComponentTypeBasedOnLib(this.CurrentLibraryId, this.CurrentLibrary, this.chkAdvSearchAllLibs.Checked) select compTypes.Value;
}
this.chkAdvSearchAllLibs.Checked is always false no matter if the check-box is checked on page and posted back or not.
Server side:
Add AutoPostBack="True" to the CheckBox. It's not posting back.
Client side:
<asp:CheckBox runat="server" ID="cb" onclick="checkboxchanged(this);" />
function checkboxchanged( sender ) {
if ( sender.checked ) {
// clicked and checked
} else {
// clicked and unchecked
}
}

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!

How to refer to a TextBox in a datalist of the same row of the Button?

I want button in the datalist OnClick gets text from both textboxes on the same row of the button.. how can i refer to that using C# keeping in mind that I want to use my own stored procedures and functions "OnClicking" buttons without using SqlDataSource Control
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<table class="auto-style2">
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("UDI") %>'></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("name") %>'></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("describtion") %>'></asp:TextBox>
</td>
<td>
<asp:Button ID="Button2" runat="server" Text="Modify" CommandArgument='<%# Eval("UDI") %>' OnCommand="Button2_Command" />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
and here is the code behind
AdminControlEntities db = new AdminControlEntities();
var x=db.sp_GetAllProducts(); //Stored procedure that returns a selection of data
DataList1.DataSource = x.ToList();
DataList1.DataBind();
till here i get my data viewed correctly, I need to Update using my own stored procedure in this example from TextBox1 and TextBox2 to the Label1 ID
ADD OnItemCommand to your mark up
<asp:DataList ID="DataList1" runat="server" OnItemCommand="Modify_ItemCommand" >
Then on Code Behind:
protected void Modify_ItemCommand(object source, DataListCommandEventArgs e)
    {
 
        /* select the row index */
        int index = Convert.ToInt32(e.Item.ItemIndex);
 
        /*To get and Textbox of selected row*/
        TextBox txtbx = (TextBox)e.Item.FindControl("TextBox1");
 
        /* Assigning Value to your textbox */
        txtbx.Text = "What ever you want here";
 
    }
You can declare the button using the property CommandName and then use the ItemCommand event controller.
Source: http://msdn.microsoft.com/es-es/library/es4e4e0e(v=vs.100).aspx
Here, a working example (Note that I'm using an UpdatePanel. Due the content of the page is going to be change, if you do not use it you will get a server error. More info here):
Test.aspx
<asp:UpdatePanel ID="upDataList1" runat="server" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:DataList ID="DataList1" runat="server" OnItemCommand="DataList1_ItemCommand">
<ItemTemplate>
<table>
<tr>
<td>
<asp:Label ID="lUID" runat="server" Text='<%# Eval("UID") %>' />
</td>
<td>
<asp:TextBox ID="tbName" runat="server" Text='<%# Eval("name") %>' />
</td>
<td>
<asp:TextBox ID="tbDescription" runat="server" Text='<%# Eval("description") %>' />
</td>
<td>
<asp:Button ID="bModify" runat="server" Text="Modify" CommandName="Modify" />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
</ContentTemplate>
</asp:UpdatePanel>
Test.aspx.cs
public partial class Test : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
var x = db.sp_GetAllProducts();
DataList1.DataSource = x;
DataList1.DataBind();
}
}
protected void DataList1_ItemCommand(Object sender, DataListCommandEventArgs e) {
String a = ((TextBox) e.Item.FindControl("tbName")).Text;
String b = ((TextBox) e.Item.FindControl("tbDescription")).Text;
((Label) e.Item.FindControl("lUID")).Text = a + " " + b;
}
}
public class db {
public String UID { get; set; }
public String name { get; set; }
public String description { get; set; }
public db(String UID, String name, String description) {
this.UID = UID;
this.name = name;
this.description = description;
}
public static List<db> sp_GetAllProducts() {
List<db> list = new List<db>();
list.Add(new db("1", "1a", "1b"));
list.Add(new db("2", "2a", "2b"));
list.Add(new db("3", "3a", "3b"));
list.Add(new db("4", "4a", "4b"));
list.Add(new db("5", "5a", "5b"));
list.Add(new db("6", "6a", "6b"));
return list;
}
}

Categories

Resources