aspx dropdown adding items how to get dropdownlist instance - c#

I want to add items to my drop down in function addItems. How to do that at runtime?
<asp:DropDownList ID="DropDownNum" runat="server" Width="50px" SelectedValue='<%#Bind("num")%>' OnLoad='addItems'>
</asp:DropDownList>
protected void addItems() {
...
foreach (NumOption option in ConfigManager.Config.NumOptions.Options)
{
numDropDown.Items.Add(option.Value);
}
}
edit: I need to get the instance of the DropDownList to call it via numDropDown, the adding itself is not the problem

You can add items like...
numDropDown.Items.Add(new ListItem("Text", "Value"));
Edit: In reference your comments, you are unable to get the Control reference in your code class. You have to find the control in the particular container e.g.
DropDownList numDropDown = (DropDownList)Container.Item.FindControl("DropDownNum");
Note: where Container is the control in your dropdownlist

numDropDown.Items.Add(new ListItem("text", option.Value));

Related

DropdownList value selected is always return first value

At the moment i have a method that retrieves a list of name from my database and return as an arraylist.
public static ArrayList GenerateFolderLocation(String username)
{
// Get User ID
SqlDataReader sqlUserID = GetUserInformation(username);
sqlUserID.Read();
int userid = int.Parse(sqlUserID["userid"].ToString());
SqlCommand cmd = new SqlCommand("SELECT distinct foldername FROM mb_folder WHERE userid=#userid", SQLGetMBoxConnection());
cmd.Parameters.AddWithValue("#userid", userid);
SqlDataReader sqldr = cmd.ExecuteReader();
ArrayList locationList = new ArrayList();
while (sqldr.Read())
{
locationList.Add(sqldr["foldername"].ToString());
}
locationList.Sort();
return locationList;
}
And in my page load method, i use DataSource and DataBind to fill up a dropdownlist i have on my main page. Note UploadLocation is the id of my dropdownlist
UploadLocation.DataSource= MBFolder.GenerateFolderLocation(Context.User.Identity.Name);
UploadLocation.DataBind();
And in my main page i have this dropdownlist and i also have a submit button
<asp:DropDownList ID="UploadLocation" runat="server"
AutoEventWireup="true" EnableViewState="true">
</asp:DropDownList>
<asp:Button ID="NewUploadFile" runat="server" Text="Upload" OnClick="NewUploadFile_Click" ValidationGroup="UploadFileValidation" AutoPostBack="true"/>
What my problem is that when i click my submit button it fires the "NewUploadFile_Click" and in that method i want to retrieve the selected value of my dropdownlist. However right now i am able to retrieve the value but it is the first value in my dropdownlist. So for example, in my arraylist there would be (test1,test2,test3) and if i select "test2" my method would retrieve "test1" instead.
In "NewUploadFile_click" i use UploadLocation.SelectedItem.Text; to get the selected value. What am i doing wrong? How can i retrieve the selected data. Thx
Try wrapping your list initialisation code within an !IsPostBack {} section in the PageLoad Event.
ie in Page_Load
if (!IsPostback)
{
... Initialise List here
}
Looks like you may be rebinding the list before you have got the data you need.
When you are calling a method to bind dropdownlist, try to add it inside
In PageLoad event:
if(!IsPostBack)
{
fillvalues();
}
So, It will not fire everytime you change your selections
Try setting AutoPostBack="true"; into your DropDownList
<asp:DropDownList ID="UploadLocation" runat="server"
AutoEventWireup="true" EnableViewState="true" AutoPostBack="true";>
</asp:DropDownList>
Confirm that you page level ViewState is enabled
and also confirm that your databinding code is inside !IsPostback condition
if (!IsPostback)
{
.... databinding code..
}

Bind a list of users controls to gridview

I desperately seeks in vain. I want to bind a List(T) of Users Controls (.ascx) to a gridview. I initialize my controls in code-behind :
List<myControl> ctrls = new List<myControl>();
myControl ctr = LoadControl("~/Control.ascx") as myControl;
ctr.Name = ...
// ...
ctrls.Add(myControl); // add new control to the collection
And after, i bind this list to Gridview control :
this.GridView1.DataSource = ctrls;
this.gridView1.DataBind();
In the Page_Load event with condition If (!IsPostBack). This does not work: the representation of the object is displayed. Whereas when I put the controls in a Panel, all worked.
Don't use a GridView for this. Use a Repeater. And bind it to the data, not to list of controls. Example:
<asp:Repeater runat="server" id="ControlsRepeater">
<ItemTemplate>
<uc:MyControl runat="server" />
</ItemTemplate>
</asp:Repeater>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
var myData=GetData(); //should return some type of ICollection representing your data to bind to
ControlsRepeater.DataSource=myData;
ControlsRepeater.DataBind();
}
}
If you want paging, then you should take advantage of lazy loading (the Entity Framework handles this for you if you use that) and the Linq functions .Take() and .Skip().

ASP.NET User Control Repeater.ItemDataBound Event Not Being Triggered

Event registered in aspx
<asp:Repeater ID="StepRepeater" OnItemDataBound="StepRepeater_ItemDataBound1" runat="server">
Tried with AutoEventWireUp true & false
Here's the method in the code behind:
public void LoadSteps(Request request)
{
Repeater StepRepeater = new Repeater();
StepRepeater.DataSource = request.Steps;
StepRepeater.DataBind();
}
protected void StepRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
}
When stepping through, it just goes straight through "StepRepeater.DataBind();" without hitting the ItemDataBound event.
Please let me know if any additional information would help.
Your OnItemDataBound value doesn't match your method name.
OnItemDataBound="StepRepeater_ItemDataBound1"
protected void StepRepeater_ItemDataBound
Remove 1 from the end of OnItemDataBound or change your method name.
Also as #Adil has stated, remove the new Repeater() line:
Repeater StepRepeater = new Repeater();
UPDATE: After reading your comment on another answer regarding adding the new Repeater() line to prevent a null reference error:
Adding new Repeater() is going to create a new instance of a Repeater control, therefore not referencing the Repeater on your ASPX markup file.
If you are receiving a null reference exception, you should check that your Inherits property in your #Page directive (usually the very top line of your ASPX file) matches the class in your .aspx.cs file, and that your CodeFile property matches your .aspx.cs filename.
You have binded event ItemDataBound to StepRepeater in html but you are assigning that datasource of newly created repeater object and no event is attached to this repeater object.
Remove this statement
Repeater StepRepeater = new Repeater();
You code will be
public void LoadSteps(Request request)
{
StepRepeater.DataSource = request.Steps;
StepRepeater.DataBind();
}
Change the name of OnItemDataBound event in html to match the code behind
<asp:Repeater ID="StepRepeater" OnItemDataBound="StepRepeater_ItemDataBound" runat="server">

Adding a Value to a Dropdown List that will trigger an event

I currently have a dropdown list being populated with values from a database. I need to add an additional value in the dropdown to allow the users to add another value. This new value will be "Add Contact" and if selected will take the user to a new page. Is this possible to do and how would I go about doing it?
You can add "Add Contact ... " as a normal text and in the SelectedIndexChanged event of the dropdown (don't remember the exact name of the event), check if the selected value is "Add Contact", call the AddContact() method.
<asp:DropDownList ID="DrpDwnLstRecords" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DrpDwnLstRecords_SelectedIndexChanged"/>
private void FillDrpDwnLstRecords()
{
DrpDwnLstRecords.Items.Clear();
ListItem listItem = new ListItem("Add Contact","addContact");
//fill the dropdown from database here
}
protected void DrpDwnLstRecords_SelectedIndexChanged(..,..)
{
string selectedRecordValue = DrpDwnLstRecords.SelectValue;
if(selectedRecordValue == "addContact")
{
//go to new page
}
}
For more help with DropDownLists and opening new page
a SO answer
DropDownList Web Server Control Declarative Syntax
DropDownList Class
How to add listitem in dropdownlist using C# behind code.
DropDownList in ASP .Net
HOW TO: Add a default ListItem to a DropDownList
Opening a New Window - How to open a new window with JavaScript

TreeView Control

I am developing an application using C#. I am using RadioButtonlist control inside a TreeView. I am getting collection of items from database. Based on the collection items I need to select the Radiobuttonlist items.
For example from the database i got the Collection in this way: Read(R) Write(W)
based on this colletion i need to set up the user permissions.
If I get your question right you want to bind that radiobutton list based on the items in the database based on the current row item on the grid. If thats the case here is your solution.
Lets say you have a Grid called myGrid, a RadioButtonList called myRadio and a HiddenField called myHidden (this is where you bind the value you have on "R" and "W")
All you have to do is when a RowDataBound Event Occurs then you have to assign the value to myRadio
for Example, you have a RadioButtonList like such
<asp:RadioButtonList ID="myRadio" runat="server">
<asp:ListItem Value="R">Read</asp:ListItem>
<asp:ListItem Value="W">Write</asp:ListItem>
</asp:RadioButtonList>
So your code behind should look like this
protected void myGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
RadioButtonList rdoAnswer = (RadioButtonList)e.Row.FindControl("myRadio");
HiddenField hdnValue = (HiddenField)e.Row.FindControl("myHidden");
rdoAnswer.SelectedValue = hdnValue.Value;
}
}

Categories

Resources