Im facing a pretty weird problem today.
I created a DropDownList which adds the selected Item to a List. The List will be binded to the ListView.
This is the Dropdown:
<asp:DropDownList ID="ddlChooseNewApplication" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem Selected="True">Bitte wählen</asp:ListItem>
<asp:ListItem Value="windows">Windows</asp:ListItem>
<asp:ListItem Value="mail">E-Mail</asp:ListItem>
<asp:ListItem Value="app1">App1</asp:ListItem>
<asp:ListItem Value="app2">App2</asp:ListItem>
<asp:ListItem Value="app3">App3</asp:ListItem>
</asp:DropDownList>
Next, when a Item has been clicked it runs the following code:
//This is a global variable
List<NewApplicationModels> applicationName = new List<NewApplicationModels>();
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = ddlChooseNewApplication.SelectedValue.ToString();
applicationName.Add(new NewApplicationModels(){ ApplicationName = value});
ListViewNewApplications.DataSource = applicationName;
ListViewNewApplications.DataBind();
}
It will be added to a List<> which should add the selected application to the ListView which looks like this:
<asp:ListView ID="ListViewNewApplications" runat="server">
<ItemTemplate>
<br /><br />
<%# Eval("ApplicationName") %><br />
<asp:Label ID="Label3" runat="server" Text="Titel"></asp:Label><br />
<asp:TextBox ID="tbNewTitle" runat="server"></asp:TextBox><br /><br />
<asp:Label ID="Label4" runat="server" Text="Beschreibung"></asp:Label><br />
<asp:TextBox ID="tbNewDescription" runat="server" TextMode="MultiLine"></asp:TextBox><br /><br />
</div>
</ItemTemplate>
</asp:ListView>
Adding a single Item to the ListView works. The problem is, if I select a new Item in the DropDown, the current object in the ListView will be overwritten. I want it to create a new Item under the current Item.
Where is the mistake?
Many thanks in advance
Editted: Just read here that static property is per application domain, not per user, So the solution should change to use Session State
//Add using on top of .cs
using System.Linq;
//In cs class
public partial class name_of_class : Page
{
private List<NewApplicationModels> applicationName = new List<NewApplicationModels>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Do page_load stuff....
Session.Remove("name_here"); //reset the Session when first page load
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//Get List from Session
applicationName = (List<NewApplicationModels>)Session["name_here"];
if (applicationName == null)
applicationName = new List<NewApplicationModels>();
string value = ddlChooseNewApplication.SelectedValue.ToString();
if (!applicationName.Any(item => item.ApplicationName == value))
{
applicationName.Add(new NewApplicationModels(){ ApplicationName = value});
Session["name_here"] = applicationName;
ListViewNewApplications.DataSource = applicationName;
ListViewNewApplications.DataBind();
}
}
}
For static property is per application domain, 2 stranger people from 2 different place browse the same page in same server (app domain) will all see it.
That means when userA change dropdownlist 2 times and the listview have 2 items, then userB browse and change dropdownlist, he may get 3 items in listview, 2 of userA and 1 of his recently choose (he may get nothing too).
Related
I am working on an asp.net application. I have a drop down list of customer account no. When i enter customer id card number in text box and click search button, the drop down should be populated with all the account numbers provided against that id card number previously. It works fine but when i add a new id card number and click search the drop down still retains the previous customer's account numbers. I want the drop down to empty and reppulate everytime i click Search and the item at value 1 i.e Other should stay constant rest of the list changes dynamically.
protected void Search_Click(object sender, EventArgs e)
{
ddl_accno.Items.Clear();
ddl_accno.Items.Add(new ListItem("Other", "0"));
string cnic = txt_cnic.Text;
BindControls.ControlBinder.BindDropDown(ddl_accno, UL.GetAccountNo(cnic),"ACCOUNT_NO","ACCOUNT_NO");
}
<td style="width:275px">
<label for="textfield">
Account no.</label>
<asp:DropDownList Font-Size="Small" ID="ddl_accno"
runat="server" AutoPostBack = "True"
Width="319px" AppendDataBoundItems="true"
onselectedindexchanged="ddl_accno_SelectedIndexChanged">
<asp:ListItem Value="0" Selected="True" Text="Select Account No"></asp:ListItem>
<asp:ListItem Value="1" Text="Other"></asp:ListItem>
</asp:DropDownList><br />
I am using UL.GetAccountNO() function to populate ddl with query. If the user selects other a text box will be visible where user can enter an account number apart from the ones in the drop down.
Pasting a sample code:
Design:
<asp:DropDownList ID="AssignedToDropDownList" runat="server" DataSourceID="UserLinqDataSource"
DataTextField="UserName" DataValueField="UserId" AppendDataBoundItems="true"
SelectedValue='<%# Bind("AssignedTo") %>'>
</asp:DropDownList>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
DDLDataBind();
}
private void DDLDataBind()
{
AssignedToDropDownList.Items.Clear();
AssignedToDropDownList.Items.Add(new ListItem("--did not assign--", "0"));
AssignedToDropDownList.DataBind();
}
I have never used user controls in C# .NET, and am working on a project where I have 3 dropdownlists, and need to put them into a user control. I was wondering how I would go about doing this. I will post the code for my dropdownlists, and a screen grab of what they currently look like, and what they should look like. Thanks.
public partial class _default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.DataBind();
DropDownList1_SelectedIndexChanged(sender, e);
DropDownList2.DataBind();
DropDownList2_SelectedIndexChanged(sender, e);
DropDownList3.DataBind();
}
}
// Drop Down List 1
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
XmlDataSource2.XPath = String.Format("mmsdata/mill[#n='{0}']/mach", DropDownList1.SelectedValue);
}
// Drop Down List 2
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
XmlDataSource3.XPath = String.Format("mmsdata/mill[#n='{0}']/mach[#n='{1}']/srn", DropDownList1.SelectedValue, DropDownList2.SelectedValue);
BindSensorList();
}
protected void BindSensorList()
{
//sender.GetType();
XmlDocument xdoc = XmlDataSource3.GetXmlDocument();
XmlNodeList nodes = xdoc.SelectNodes(XmlDataSource3.XPath);
var sensors = new List<Sensor>();
foreach (XmlNode node in nodes)
{
sensors.Add(new Sensor { id = node.Attributes["n"].Value, name = node.InnerText });
}
DropDownList3.DataSource = sensors;
DropDownList3.DataValueField = "id";
DropDownList3.DataTextField = "name";
DropDownList3.DataBind();
}
What I want them to look like
What they look like
The easiest way to add your dropdown to the user control is to create a user control in the project solution, and then put the asp.net webform code in the ui and you can then write a code behind for it same way you create a web forms.
Sample User Control
<%# Control Language="C#" ClassName="SampleUserControl" %>
<h3> <u>User Control</u> </h3>
<script runat=server>
</script>
Drop down 1: <asp:DropDownList id="ColorList"
AutoPostBack="True"
OnSelectedIndexChanged="Selection_Change"
runat="server">
<asp:ListItem Selected="True" Value="White"> White </asp:ListItem>
<asp:ListItem Value="Silver"> Silver </asp:ListItem>
<asp:ListItem Value="DarkGray"> Dark Gray </asp:ListItem>
<asp:ListItem Value="Khaki"> Khaki </asp:ListItem>
<asp:ListItem Value="DarkKhaki"> Dark Khaki </asp:ListItem>
</asp:DropDownList>
<asp:label id="Label1" runat=server/>
You can use a user control on a page and dynamically load its content, just initialise it on the page you wish to use it on and pass in values the same way you load a class/page
Im using a repeater to display some products in an online shop for a school project. This is how the front end looks with the repeater
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="rptList_ItemCommand">
<ItemTemplate>
<span style="float:left; padding:25px;" class="backgrnd">
<asp:ImageButton ID="imgProd" runat="server" style="width:150px; height:150px;" ImageUrl='<%# DataBinder.Eval(Container.DataItem, "productImg")%>' CommandArgument='<%# DataBinder.Eval(Container.DataItem, "productID")%>' CommandName="ViewIndividProd"/><br />
<p style="clear:left;">
<asp:Label ID="lbName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "productName")%>' /><br />
<asp:Label ID="lbUnitPrice" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "unitPrice")%>'/><br />
<asp:Label ID="lbRatings" runat="server" Text=''>Ratings</asp:Label><br />
<asp:LinkButton ID="linkCart" runat="server" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "productID")%>' CommandName="AddToCart">Add to Cart</asp:LinkButton>
</p>
</span>
</ItemTemplate>
</asp:Repeater>
As you can see I've added on the OnItemCommand in the Repeater tag so that this is invoked whenever one of the buttons(image/link) is fired. That works perfectly fine for both commandname AddToCart and ViewIndividProd. However, i want to store the the productid of a specific item that was invoked by the particular button. In my case now, it only stores ONE productid in the arraylist at a time and 'forgets' the productid that was stored previously when another linkbutton is clicked.
Question How do i make it such that everytime a linkbutton in the repeater is fired, it remembers the productid pertaining to the linkbutton that was fired and save these ids into the arraylist?
This is how the back end looks
ArrayList cart = new ArrayList();
protected void rptList_ItemCommand(object sender, RepeaterCommandEventArgs e) {
if (e.CommandName == "ViewIndividProd") {
Session["productID"] = e.CommandArgument.ToString();
Response.Redirect("IndividProduct.aspx");
}
if (e.CommandName == "AddToCart") {
string prodid = e.CommandArgument.ToString();
cart.Add(prodid);
Session["ShoppingCart"] = cart;
Response.Redirect("IndividCat.aspx");
}
msg.Text = "Shopping cart: " + String.Join(",", cart.ToArray());
}
Your feedback would be much appreciated.
You need to understand the Asp.net Page life cycle.
A new instance of your Page object is created on every request.
Values from your input are populated into it.
Your array list is getting recreated every time.
If you want the values to persist, you will have to store your arraylist in the ViewState or the Session
Refer: How to: Save Values in View State
void Page_Load(object sender, EventArgs e)
{
if (ViewState["arrayListInViewState"] != null)
{
PageArrayList = (ArrayList)ViewState["arrayListInViewState"];
}
else
{
// ArrayList isn't in view state, so we need to create it from scratch.
PageArrayList = CreateArray();
}
// Code that uses PageArrayList.
}
We can store comma separated or JSON value in either Session or hidden variable (If you are on the same page and opening new page in different tab then we can use hidden variable also). So every time an button has been click we can append the product id.
I'm having a very hard time figuring out what I'm doing wrong here. In my Edit Item Template I have the following code for my drop down list:
<asp:DropDownList ID="dd_is_active" runat="server" AppendDataBoundItems="true"
DataValueField="Enabled">
<asp:ListItem Text="Yes" Value="1"></asp:ListItem>
<asp:ListItem Text="No" Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:HiddenField ID="is_activeTextBox" runat="server" Value='<%# Bind("Enabled") %>' />
Here is my aspx.cs code:
protected void ListView1_ItemInserting(object sender, ListViewInsertEventArgs e)
{
e.Values["SUB_last_modified_date"] = DateTime.Now.ToString();
e.Values["SUB_last_modified_by_user_id"] = HttpContext.Current.User.Identity.Name;
e.Values["SUB_last_modified_by_user_name"] = Session["UserName"].ToString();
e.Values["Enabled"] = ((DropDownList)(sender as ListView).InsertItem.FindControl("dd_is_active")).SelectedValue;
e.Values["Category_ID"] = ((DropDownList)(sender as ListView).InsertItem.FindControl("dd_category")).SelectedValue;
}
protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
e.NewValues["SUB_last_modified_date"] = DateTime.Now.ToString();
e.NewValues["SUB_last_modified_by_user_id"] = HttpContext.Current.User.Identity.Name;
e.NewValues["SUB_last_modified_by_user_name"] = Session["UserName"].ToString();
}
It seems something is either missing from my .cs code or I have the values of 1 and 0 bound incorrectly in the html code. This exact same code works for the Insert Item Template, but the Update (or Edit Item Template) is not working correctly.
When I try to edit an item in my table I get an error stating the input string is in an incorrect format. I know it's trying to bind the Text of "Yes" or "No" but I need to ind to the Values of either "0" or "1". Any help is greatly appreciated!
I think your syntax is wrong for HiddenField value.
Instead of this
<asp:HiddenField ID="is_activeTextBox" runat="server" Value='<%# Bind("Enabled") '>' />
It should be
<asp:HiddenField ID="is_activeTextBox" runat="server" Value='<%# Bind("Enabled")%>' />
I have the following code in my aspx page:
<asp:Button id="display_button" runat="server" Text="Display" OnClick="Button1_Click" />
<asp:Button id="edit_button" runat="server" Text="Edit" OnClick="Button2_Click" />
<asp:Button id="save_button" runat="server" Text="Save" OnClick="Button3_Click" Visible="false" />
<asp:MultiView id="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View id="View1" runat="server">
<asp:FormView id="view_program" runat="server">
<ItemTemplate>
<%# Eval("status").ToString().Trim() %>
</ItemTemplate>
</asp:FormView>
</asp:View>
<asp:View id="View2" runat="server">
<asp:FormView id="edit_program" runat="server">
<ItemTemplate>
<asp:DropDownList id="p_status" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:FormView>
</asp:View>
</asp:MultiView>
and the following functions attached to the buttons in the code-behind page:
protected void Button1_Click(object sender, EventArgs e)
{
MultiView1.SetActiveView(View1);
save_button.Visible = false;
}
protected void Button2_Click(object sender, EventArgs e)
{
MultiView1.SetActiveView(View2);
save_button.Visible = true;
}
protected void Button3_Click(object sender, EventArgs e)
{
DropDownList p_status = edit_program.FindControl("p_status") as DropDownList;
var status = p_status.SelectedValue;
Label1.Text = status;
//save_button.Visible = false;
//MultiView1.SetActiveView(View1);
}
The idea being, that there are two views, the first displays the information, if the user wants to edit the information, they click button 2 which changes the view to the edit mode, which has the controls (drop downs, text fields, etc). It also makes the 'save' button appear.
What I am trying to make happen is, when the save button is clicked, it will grab all of the values from the various fields, update the object and then update the database. Then it would flip back to view1 with the updated info.
Problem is, as you can see in void Button3_Click, I try grab the values from the control, p_status, but it only gets the original value. example, the menu has three values, 'Green', 'Yellow', and 'Red'. Green is the default value and is selected when view2 is displayed. However, if I select Yellow or Red, and click save, rather than the label being updated to display one of those two values, it always displays Green.
Any ideas?
edit: page load function per request below
protected void Page_Load(object sender, EventArgs e)
{
try
{
Person myPerson = new Person(userid);
TestProgram myProgram = new TestProgram(id);
List<TestProgram> program = new List<TestProgram> { myProgram };
view_program.DataSource = program;
view_program.DataBind();
edit_program.DataSource = program;
edit_program.DataBind();
DropDownList p_status = edit_program.FindControl("p_status") as DropDownList;
p_status.Items.Add(new ListItem("Green", "Green"));
p_status.Items.Add(new ListItem("Yellow", "Yellow"));
p_status.Items.Add(new ListItem("Red", "Red"));
//myProgram.Status = "Red";
p_status.SelectedValue = myProgram.Status;
}
catch (Exception ex)
{
Response.Write(ex);
Label1.Text = ex.ToString();
}
}
Whoops...missed a little someting.. my
bad
when asp.net is not behaving as expected this is your best friend: MSDN: ASP.NET PAGE LIFECYLE
Upon Further Review...
there are a couple of problems here. your drop down list control with an id of "p_status" is contained inside a multiview (I forgot about what that meant...) you need to move the code to populate p_status into pre-render after checking to see if Multiveiw1.ActiveView = View2. Since it will always be a post back you need to bind values late in the page cycle