How to access data of controls inside usercontrol in c# - c#

I have added a user control dynamically which contains dropdowns'. Loading User control is iterated 'I' times according to the condition. Now, I need to access the dropdowns' selected item. I have created an accessor function to get the dropdown selected values, but it is giving me the default value, which is "00" of the drop-down.
If someone needs additional Information to solve my problem,
kindly ask me.
Adding user control dynamically:
for (int i = 0; i < 3; i++)
{
//DailyControl is a userControl
DailyControl w1 = (DailyControl)LoadControl("~/DailyControl.ascx");
//InputPanel is a panel where user control is added.
InputPanel.Controls.Add(w1);
}
DailyControl.ascx
Select the Time:
<asp:DropDownList ID="clock" runat="server">
<asp:ListItem Text="am" />
<asp:ListItem Text="pm" />
</asp:DropDownList>
DailyControl.ascx.cs // accessor function to get the dropdown
public string Clock
{
get
{
return clock.SelectedItem.Text.ToString();
}
}

Instead of add controls dinamically, you can use a Repeater on aspx page.
In the Repeater you can bind a DropDownList (or a control containing the DropDownList) and get
myDropDownList.SelectedValue
(or SelectedItem)

Related

Update DropdownList dynamically within a Modal

There is an issue I have not been able to solve which is where there is an 'Add Item' button on a form. When clicked this opens a Modal window which contains two dropdown lists. The first dropdown list is prepopulated with a set of items and based on this selection, the 2nd dropdown box ideally needs to update with its own set of items.
This is the first Dropdown List which contains the Type
<asp:DropDownList ID="DDLType" CssClass="form-control" runat="server" OnSelectedIndexChanged="LoadSubTypes" AutoPostBack="true">
<asp:ListItem Value="Automobile">Automobile</asp:ListItem>
<asp:ListItem Value="Aeroplane">Aeroplane</asp:ListItem>
<asp:ListItem Value="Boat">Boat</asp:ListItem>
</asp:DropDownList>
This is the second Dropdown List which currently sits empty until a selection is made from the first dropdown list.
<asp:DropDownList ID="DDLSubType" CssClass="form-control" runat="server">
</asp:DropDownList>
With the first DDL where there is an OnSelectedIndexChange, this is the code behind.
protected void LoadSubTypes(object sender, EventArgs e) {
string strSubTypeList = "";
switch (DDLType.SelectedValue)
{
case "Automobile":
strSubTypeList = "Car#Motorbike#Scooter";
break;
case "Aeroplane":
strSubTypeList = "Commercial#Private";
break;
case "Boat":
strSubTypeList = "Boat#Jetski";
break;
}
StringBuilder sbSubTypes = new StringBuilder();
Char delimiter = '#';
String[] substrings = strSubTypeList.Split(delimiter);
foreach (var substring in substrings)
{
DDLSubType.DataTextField = substring;
DDLSubType.DataValueField = substring;
DDLSubType.DataBind();
} }
Normally this type of setup works well for me, but the only difference this time is I have them loaded into a Modal. What happens when I make a selection from the DDL is that the modal closes and causes the postback. This resets any values that were then changed dynamically.
My ideal behavior here is that when a selection is made on the first DDL, the 2nd DDL updates within the modal and do not close.
Any help would be greatly appreciated!
I think you are saying that when I select an item from a dropdown list, then its relevent options will be shown on the next dropdown. You will have to use jquery ajax(it will be more easy).
When an item is selected from a dropdown, its value will be passed using ajax, which will without refreshing your page get your dropdown.
e.g.
<select class="form-control" id="Departments" ><option value="">-Select Department-</option>
<option value="17">No Department</option>
<option value="19">Men</option>
<option value="1018">Danial</option>
</select>
JavaScript with jquery:
$("#Departments").change(function () {
var deptId = $(this).select("option:selected").val();
$.ajax(
{
url: "/Categories/M_Level2/" + deptId
}).done(function (categories)
{
$("#category").html(categories);
});
In url, Categories is the controller and M_Level2 is the action that is getting a value deptId and on that basis returning a PartialView and then adding it on #category

asp.net dropdownlist does not remember choice

I'm currently running into a head-scratching bug in my ASP.NET Windows Form App. I have two DropDownList, implemented them in the same way, yet they behave differently.
The problem:
When selecting an item in the DropDownList "GroepSelect", the page refreshes (as intended), but resets it's SelectedIndex to the first item.
When selecting an item in the DropDownList "VakSelect", the page refreshes, but also remembers it's SelectedIndex value.
It's doing this behavior consistently, yet I am unable to discover what I do wrong.
My Code:
In my HTML code, I have two DropDownList Controls.
<div>
<asp:DropDownList runat="server" ID="GroepSelect" AutoPostBack="true" AppendDataBoundItems="true" />
<asp:DropDownList runat="server" ID="VakSelect" AutoPostBack="true" AppendDataBoundItems="true" />
</div>
I'm populating the controls in my C# code:
protected void Page_Load(object sender, EventArgs e) {
Database db = new Database();
if (!IsPostBack) {
GroepSelect.DataSource = GenereerDummyGroepen(); // returns a List<ListItem>
GroepSelect.DataTextField = "Text";
GroepSelect.DataValueField = "Value";
GroepSelect.DataBind();
GroepSelect.SelectedValue = "1";
VakSelect.DataSource = db.GetVakken(); // returns a List<Vak>
VakSelect.DataTextField = "Omschrijving";
VakSelect.DataValueField = "Id";
VakSelect.DataBind();
VakSelect.SelectedValue = "1";
}
// Use the SelectedValue to determine which data to get out of the database
Medewerkers = db.GetMedewerkers(int.Parse(GroepSelect.SelectedValue));
Opdracht = db.GetOpdrachten(int.Parse(VakSelect.SelectedValue)).First();
Resultaten = db.GetResultaten(Opdracht.Id, int.Parse(GroepSelect.SelectedValue));
GenereerTabel();
}
As requested, my code for GenereerDummyGroepen() is the following:
private List<ListItem> GenereerDummyGroepen() {
return new List<ListItem>()
{
new ListItem("Groep 1", "1"),
new ListItem("Groep 2", "1")
};
}
Why I implemented it this way?
I try to populate a custom-made pivot table based on the content of Medewerkers, Opdracht and Resultaten. The content of those lists, depends on the selected item in the DropDownList control. The expected behavior of those controls is, that on the moment those are changed, the table should re-populate. The strategy I follow here, is that a page-postback is being processed, and using the AppendDataBoundItems=true remembers the DropDownList contents so that on the newly refreshed page I can generate the table.
My Question
I'm looking for the answer for: why is there a consistent different behavior? Is it the fact that the ListItem class differs in behavior from my custom class Vak?
Here I guess issue is with you function
GenereerDummyGroepen();
Please put your code here. In your code there is value field might have same data for all listItem. Because of that it is changing default to firstIndex as all values are same.

Find dropdown values on user control inside repeater asp.net

I am trying to access DropDownList selected value from user control which is placed inside Repeater's ItemTemplate.
string ddlBeneficiaryTeam2 = ((UserControl_TeamFilter)(rptBeneficiaries.FindControl("ucBeneficiaryTeam"))).TeamSelectedValue;
rptBeneficiaries -Repeater control
ucBeneficiaryTeam -User control
ddlteam -DropDownList Name its in user control.
You can use FindControl to locate the correct Control by going up the control tree.
DropDownList drp = Repeater1.Items[i].FindControl("WebUserControl1").FindControl("DropDownList1") as DropDownList;
First you access the correct repeater item by an index and then by ID of the User Control and then the DropDownList inside the control.
first divide this to two part
1-first in your Usercontrol create public property that represents value of your DropDown
public class UserControl_TeamFilter : System.Web.UI.UserControl
{
....
public string TeamSelectedValue
{
get { return ddlteam.SelectedValue; }
}
...
2-now you just need to find and cast your Usercontrol in repeater item as below
(rptBeneficiaries.Items[i].FindControl("ucBeneficiaryTeam") as UserControl_TeamFilter).TeamSelectedValue

On Postback, the DataTable data source for a Repeater is empty?

Background
I have a User Control (an .ascx file) which is being dynamically inserting into an asp:PlaceHolder control on a page. That User Control contains an asp:Repeater, which I'm binding to a DataTable.
Theoretically, on the User Control's first load the DataTable is initialized and 3 empty rows are added. A button on the User Control adds additional empty rows to the Repeater, one at a time.
Problem
The issue is that after any PostBack event on the page (namely the button in this example being clicked), the DataTable for the Repeater is empty.
User Control (.ascx)
(simplified)
<asp:TextBox ID="controlOutsideRepeater" runat="server" />
<asp:Repeater ID="myRepeater" runat="server">
<ItemTemplate>
<p><asp:Textbox ID="firstControlInRepeater" runat="server" text='<%# DataBinder.Eval(Container.DataItem, "A") %>' /></p>
<p><asp:Textbox ID="secondControlInRepeater" runat="server" text='<%# DataBinder.Eval(Container.DataItem, "B") %>' /></p>
</ItemTemplate>
</asp:Repeater>
<asp:LinkButton ID="addItemButton" runat="server" Text="Add Item" onclick="addNewItem" />
Code Behind (.ascx.cs)
(also simplified)
public DataTable items {
get {
object i = ViewState["items"];
if (i == null) {
DataTable t = new DataTable();
t.Columns.Add("A");
t.Columns.Add("B");
// add 3 blank items/rows:
t.Rows.Add(t.NewRow());
t.Rows.Add(t.NewRow());
t.Rows.Add(t.NewRow());
ViewState["items"] = t;
return t;
} else {
return (DataTable)i;
}
set { ViewState["items"] = value; }
}
protected void Page_Init(object sender, EventArgs e) {
myRepeater.DataSource = this.items;
myRepeater.DataBind();
}
public void addNewItem(object sender, EventArgs e) {
DataRow r = this.items.NewRow();
this.items.Rows.Add(r);
myRepeater.DataBind();
}
Behavior
The first time the UserControl is loaded, the Repeater contains 3 empty items: good! However, after entering some text in the textboxes both inside and outside the repeater and clicking the "Add Item" LinkButton, the page does a refresh/postback and shows 4 empty items, however the textbox -outside- the Repeater retains it's text. Clicking the "Add Item" LinkButton again also performs a postback and still shows 4 empty items, yet the TextBox outside the Repeater again retains it's text.
My Crazy Guess
I've tried wrapping the Repeater databinding in a (!Page.IsPostBack), but this prevented the Repeater from -ever- being bound, as the UserControl is only programmatically added to the page after a PostBack (a button on the Page adds the UserControl on a click, and then the Page checks each PostBack to see if there should be a user control present and re-adds it to the Page if needed). So I'm guessing there's a problem with the Page re-creating the User Control on every PostBack, but can't explain why the TextBox outside the Repeater would retain it's value, and why the ViewState doesn't seem to remember my item (on each postback ViewState["items"] is null and gets re-built within the getter).
HELP!
The problem is you are data binding every single request when really you only want to data bind on the first request. Since you don't data bind on the first page load, you will have to check if you are data bound in a way other than !Page.IsPostBack. You could add a property to your user control to handle this and then check against that every page load / page init.
Update: With more details from comments
I see your AddItem() now. I've had problems using viewstate this way though I'm not entirely sure why. I've had to do it more like the following:
public void addNewItem(object sender, EventArgs e) {
DataTable theItems = this.items;
DataRow r = theItems.NewRow()
theItems.Rows.Add(r);
this.items = theItems
myRepeater.DataBind(); //I'm not sure if this belongs here because of the reasons said before
}

asp.net - problems getting dropdownlist

I am using a code behind function to bind my dropdownlist dynamically, when a user changes the dropdownlist and submit a purchase, the selectedvalue is always empty.
I have tried both ddl.SelectedItem.ToString(); and ddl.SelectedValue.ToString(); but none work. Also for these 2 code behind functions below, I can't seem to use void methods instead of a function that needs a returning value and a parameter, is there anyway to use void methods without parameters? Any advice is appreciated.
Thanks.
<%# FormattedSize((string)Eval("Size")) %>
<%# FormattedGetSize((string)Eval("Size")) %>
inline:
<asp:DropDownList ID="DropDownList1" runat="server" OnDataBinding='<%# FormattedSize((string)Eval("Size")) %>'></asp:DropDownList>
<a href='AddToCart.aspx?CategoryId=<%# Eval("CategoryId") %>&&ProductId=<%# Eval("ProductId" ) %>&&Size=<%# FormattedGetSize((string)Eval("Size")) %>' style="border: 0 none white;">
Code Behind:
protected string FormattedSize(string size)
{
if (size.Contains("s"))
{
DropDownList ddl = (DropDownList)FormView_Product.Row.Cells[0].FindControl("DropDownList1");
ddl.Items.Add("S");
}
if (size.Contains("m"))
{
DropDownList ddl = (DropDownList)FormView_Product.Row.Cells[0].FindControl("DropDownList1");
ddl.Items.Add("M");
}
if (size.Contains("f"))
{
DropDownList ddl = (DropDownList)FormView_Product.Row.Cells[0].FindControl("DropDownList1");
ddl.Items.Add("Freesize");
}
return null;
}
protected string FormattedGetSize(String Size)
{
DropDownList ddl = (DropDownList)FormView_Product.Row.Cells[0].FindControl("DropDownList1");
string selectedSize = ddl.SelectedItem.ToString();
return selectedSize;
}
The reason why it doesn't work is because.. "you're doing it wrong". You're expecting that the <a href=.. will change based on the user interaction but instead it is already generated when user receives the page. If you want the link to change based on the dropdown, you'd have to have either:
a postback on dropdown selection, then the link would change...
you could change the href with some javascript by attaching event on dropdown selection
What you do in your Page_Load method? Do you check to see if the current request is a post back or not (using IsPostBack)?
If so, check for IsPostBack and bind your DropDownList to the underlying data source only on Get requests.

Categories