asp.net - problems getting dropdownlist - c#

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.

Related

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.

Get asp:Hyperlink data-attribute through onclick event

I have a asp:Hyperlink with a data-attribute containing a value (a number in this case).
<asp:HyperLink ID="hypTest" href="testwebsite.com" CssClass="button-close" data-test="1" runat="server" Text="Testlink" onclick="dosomething"></asp:HyperLink>
How can I access the data attribute from this HyperLink in the codebehind when a user clicks that exact link. (there will be multiple similar links)
Also note that the onclick shown above does not work for me.
It does not access the dosomething method.
protected void dosomething()
{
//get the data-test value
}
What would be the best way to achieve this?
Thanks in advance.
If you want the server click event - use LinkButton instead of using Hyperlink.
<asp:LinkButton ID="hypTest" CssClass="button-close" data-test="1" runat="server" Text="Testlink" onclick="dosomething"></asp:LinkButton>
For the dosomething event do it like this:
protected void dosomething(object sender, EventArgs e)
{
}
For the data attribute. Take it from the Attributes Collection.
string testData = hypTest.Attributes["data-test"]

Javascript values not updating after dropdown selection

I have a value that I'm passing from the server side C# code to the client side javascript that I need to update based on a dropdown selection. The value gets changed as required in my C# logic but the value change is never picked up by the client.
Here is my C# code setting the value
protected void ddlCurrency_OnSelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlCurrencyType = (DropDownList)upFilter.FindControl("ddlCurrency");
CurrencyId = int.Parse(ddlCurrencyType.SelectedItem.Value);
}
private void SetCurrencySymbol()
{
if (CurrencyId == 2)
{
CurrencySymbol = "€";
}
else
{
CurrencySymbol = "$";
}
}
And my javascript variable
var currencySymbol = "<%=CurrencySymbol%>";
The SetCurrencySymbol method is called in a if(!Page.IsPostBack) condition.
Here is my dropdownlist code
<asp:DropDownList runat="server" ID="ddlCurrency" OnSelectedIndexChanged="ddlCurrency_OnSelectedIndexChanged" AutoPostBack="True" onChange="setCurrencySymbol">
</asp:DropDownList>
That javascript variable needs to get set to the C# value after a new item is selected from the dropdown. The original value from when the page loaded is retained after a new selection is made however. Any help is appreciated. Thanks in advance.

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
}

Dropdownlist in masterpage value not updated after new selected

I would like some help with the following problem. I have a dropdownlist implemented in my masterpage. It has an sql data source from which it loads the values of companies. Depending on which value(company) selected, it shows that value in a label on a different page.
The ddl which is in the masterpage is ofc still visible and should display the selected value which it does at the 1st time a value is selected. But when i select another value in the ddl it shows the value which was 1st selected and so on. So it doesn't update or something.
My code:
This is the onselectedIndexChanged event handler:
protected void DropDownListType_SelectedIndexChanged(object sender, EventArgs e)
{
String input1 = DropDownListType.Text;
String input2 = DropDownListType.SelectedValue;
String url = "~/test.aspx?pcompany="+input1;
DropDownListType.SelectedValue = input2;
Session["Company"] = input2;
Response.Redirect(url);
}
and this is the code i'm using in my Page_load method from the masterpage:
if (Session["Company"] != null)
{
DropDownListType.SelectedValue = (String)Session["Company"];
}
If I remove this last piece of code from my page_load method it updates the label with value on the redirected page but it resets my ddl to default value instead of keeping it at 4 when value 4 selected.
I hope this is a bit clear to you all. Any help is appreciated. Ty in advance.
try setting the label value in the PreRender() method. The problem you're having is with the page life cycle. I would change your OnLoad method to use
if(!IsPostBack) {
if (Session["Company"] != null)
{
DropDownListType.SelectedValue = (String)Session["Company"];
}
}
This way you're only setting it once when the page loads and from then on the page will set the selected value automatically using viewstate.
The Load event is fired before the SelectedIndexChanged event, that's why you don't have it set in Session yet.
See ASP.NET Page Life Cycle
just set the AutoPostback property of the DropDownList to true and then it will work.
This is because otherwise the onselectedIndexChanged will be called only on PostBack from a button or any other field.
And also, as the above answer says, use this code:
if(!IsPostBack) {
if (Session["Company"] != null)
{
DropDownListType.SelectedValue = (String)Session["Company"];
}
}

Categories