ASP:DropDownList in ItemTemplate: Why is SelectedValue attribute allowed? - asp.net

This piece of code
<asp:DropDownList runat="server" ID="testdropdown" SelectedValue="2">
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
<asp:ListItem Text="3" Value="3"></asp:ListItem>
</asp:DropDownList>
yields this error:
The 'SelectedValue' property cannot be
set declaratively.
Yet, this is a legal and commonly used edit template for databound GridViews. The SelectedValue attribute certainly appears to be declaratively set here.
<EditItemTemplate>
<asp:DropDownList runat="server"
ID="GenreDropDownList"
DataSourceID="GenreDataSource"
DataValueField="GenreId"
DataTextField="Name"
SelectedValue='<%# Bind("Genre.GenreId") %>'>
</asp:DropDownList>
</EditItemTemplate>
The question is: what is the difference between the cases when you are allowed to set it declaratively and those in which you are not? The error message implies that it's never allowed.

in markup use SelectedValue='<%# "32" %>' syntax .(note the order of single and then the double quotes in the following example ):
<asp:DropDownList ID="ddlField" SelectedValue='<%# "32" %>'
runat="server" DataTextField="Name" DataValueField="ID" >
</asp:DropDownList>
or in code-behind just after DataBinding .(example):
ddlField.DataSource = Fields.SelectAll();
ddlField.DataBind();
ddlField.SelectedValue = "32";

It means you cannot set it through the designer.
The correct way is:
<asp:DropDownList runat="server" ID="testdropdown">
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2" Selected></asp:ListItem>
<asp:ListItem Text="3" Value="3"></asp:ListItem>
</asp:DropDownList>
The reason the bound method works is because the value isn't selected in design mode but at runtime after the control is bound to a datasource
The DropDownList.SelectedValue method is meant to be applied at runtime hence the error about not being able to set it 'decoratively'

Related

Dropdownlist onselectedindexchanged not firing

I have a datagrid that has dropdowns in one column :
<asp:TemplateColumn HeaderText="">
<ItemStyle HorizontalAlign="Center"></ItemStyle>
<ItemTemplate>
<asp:Label runat="server" ID="lblResultId" Visible="false" text='<%# DataBinder.Eval(Container, "DataItem.CurrentId", "{0:g}") %>'/>
<asp:DropDownList ID="ddlCurrentValue" DataTextField="Description" DataValueField="Id" Runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlCurrentValue_OnSelectedIndexChanged">
<asp:ListItem Text="" Value="0" Selected="True"></asp:ListItem>
<asp:ListItem Text="1" Value="1">1</asp:ListItem>
<asp:ListItem Text="2" Value="2">2</asp:ListItem>
<asp:ListItem Text="3" Value="3">3</asp:ListItem>
<asp:ListItem Text="4" Value="4">4</asp:ListItem>
<asp:ListItem Text="5" Value="5">5</asp:ListItem>
<asp:ListItem Text="6" Value="6">6</asp:ListItem>
<asp:ListItem Text="7" Value="7">7</asp:ListItem>
<asp:ListItem Text="8" Value="8">8</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
I set the selected value for each dropdown based on a value taken from the database on ItemDataBound.
Now if the user changes the value of one of the dropdowns, i would like to save the value from that dropdown.
My id is that i have the database-id in lblResultId and use that to save the selectedvalue from the dropdown to the database via a linq query. However, i am already stuck on the 'onselectedindexchanged' for the dropdownlists not firing.....
Any suggestions how to procede or how to do this differently ?

validate a combination of different fields

aspx page
<asp:Label ID="Label1" runat="server" Text="Date of Birth: "></asp:Label>
<asp:Label ID="dob_msg_lbl" runat="server" Font-Size="Medium" ForeColor="Red" Text="invalid date of birth" visible="False"></asp:Label>
<br />
<asp:TextBox ID="day_tb" runat="server" MaxLength="2" Width="15px"></asp:TextBox> <asp:Label ID="Label4" runat="server" Text="/" Font-Bold="True"></asp:Label>
<asp:DropDownList ID="month_ddl" runat="server">
<asp:ListItem Value=""></asp:ListItem>
<asp:ListItem Value="Jan">January</asp:ListItem>
<asp:ListItem Value="Feb">Feb</asp:ListItem>
<asp:ListItem Value="Mar">Mar</asp:ListItem>
<asp:ListItem Value="Apr">Apr</asp:ListItem>
<asp:ListItem Value="May">May</asp:ListItem>
<asp:ListItem Value="Jun">Jun</asp:ListItem>
<asp:ListItem Value="Jul">Jul</asp:ListItem>
<asp:ListItem Value="Aug">Aug</asp:ListItem>
<asp:ListItem Value="Sep">Sep</asp:ListItem>
<asp:ListItem Value="Oct">Oct</asp:ListItem>
<asp:ListItem Value="Nov">Nov</asp:ListItem>
<asp:ListItem Value="Dec">Dec</asp:ListItem>
</asp:DropDownList> <asp:Label ID="Label5" runat="server" Text="/" Font-Bold="True"></asp:Label> <asp:TextBox ID="year_tb" runat="server" Width="30px" MaxLength="4"></asp:TextBox>
aspx.vb page
Dim dobStr As String = day_tb.Text + " " + month_ddl.SelectedValue + " " + year_tb.Text
Try
dob = Convert.ToDateTime(dobStr)
Catch ex As Exception
dob_msg_lbl.Visible = True
End Try
Currently I am mimicking the asp.net's validation functions by setting dob_msg_lbl.visible to true when Convert.ToDateTime results in an exception.
The problem with such a method is that the validation only occurs when the form is submitted.
I want to validate it on the fly, just like what happens when you use RequiredFieldValidator and RegularExpressionValidator.
Is it to possible to use something such as the CustomValidator to validate a combination of textbox and dropdownlist on the fly?
You can try to use CustomerValidator as explained here
http://www.codeproject.com/Articles/9522/CustomValidator-dependent-on-multiple-controls
Or
you can create a validate function with your logic, and call it on the Selection change event for dropdown and text change event of TextBox. So anytime, any of those thing changes that will trigger the event and will call your validate function.

ASP.NET RequiredFieldValidator : How can i bind value to " InitialValue " property?

I have the following code
<div>
<asp:DropDownList ID="testDropDownList" runat="server" ValidationGroup="testValidationGroup">
<asp:ListItem Value="Choose">[ Select Item ... ]</asp:ListItem>
<asp:ListItem Value="True">Yes</asp:ListItem>
<asp:ListItem Value="False">No</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="testRequiredFieldValidator" runat="server" ValidationGroup="testValidationGroup"
ErrorMessage="*" InitialValue="Choose" ControlToValidate="testDropDownList"></asp:RequiredFieldValidator>
<br />
<asp:Button ID="testButton" runat="server" OnClick="testButton_Click" Text="Button"
ValidationGroup="testValidationGroup" />
<br />
</div>
in which i validate Dropdownlist by RequiredFieldValidator
If changed the value of initialvalue property to read from static property in stactic classs .. but it always give me emtpy string in runtime unless this property have the value "Choose" ...
<asp:DropDownList ID="testDropDownList" runat="server" ValidationGroup="testValidationGroup">
<asp:ListItem Value="Choose">[ Select Item ... ]</asp:ListItem>
<asp:ListItem Value="True">Yes</asp:ListItem>
<asp:ListItem Value="False">No</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="testRequiredFieldValidator" runat="server" ValidationGroup="testValidationGroup"
ErrorMessage="*" InitialValue='<%# Util.ChooseValue %>' ControlToValidate="testDropDownList">
</asp:RequiredFieldValidator>
<br />
<asp:Button ID="testButton" runat="server" OnClick="testButton_Click" Text="Button"
ValidationGroup="testValidationGroup" />
Could Any one help me to know what's the issue in my code ??
Please call
testRequiredFieldValidator.databind()
in page load event and let me know if this is still an issue.
Set InitialValue of RequiredFieldValidator on page_load event in aspx.cs page.

Required Field Validator for drop down list Dynamic

<asp:DropDownList ID="ddTitle" runat="server" DataTextField="TitleName" DataValueField="TitleId"ValidationGroup="t1">
</asp:DropDownList>
<asp:RequiredFieldValidator runat="server" ID="ReqDropDnw" ControlToValidate="ddTitle" Display="Dynamic" ValidationGroup="t1" InitialValue="<-- Select Title-->" ErrorMessage="Please Select Title">
</asp:RequiredFieldValidator>
I have used this but it's not working, can I have a proper solution for it
My dropdown list is a dynamic.
Use like this way...
<asp:DropDownList ID="ddl" runat="server">
<asp:ListItem Text="Select One" Value=""></asp:ListItem>
<asp:ListItem Text="abc" Value="1"></asp:ListItem>
<asp:ListItem Text="xyz" Value="2"></asp:ListItem>
</asp:DropDownList>
Now you can use required field validator for this dropdownlist.....
After binding data from DB you can use add one empty item to list like:
ddTitle.Items.Insert(0, "");
And now Required field validatior will work for this dropdown.

Databinding of RadioButtonList using SelectedValue...possible?

I am databinding a GridView to an object datasource. The gridview contains a TemplateField which contains a RadioButtonList with ListItems defined inline.
I want to be able to databind the SelectedValue of the RadioButtonList to the same underlying table as the other grid columns, but it doesn't work!
Do I have my syntax wrong, or is this impossible and requires looping code to individually select the proper item in each row?
<llblgenpro:LLBLGenProDataSource ID="llbComputerApplication" DataContainerType="EntityCollection" runat="server"></llblgenpro:LLBLGenProDataSource>
<asp:GridView ID="gridComputerApps" DataSourceID="llbComputerApplication" runat="server" AutoGenerateColumns="False"
EmptyDataText ="NO APPLICATIONS FOUND FOR THIS COMPUTER."
DataKeyNames="ComputerID, ApplicationID" EnableViewState="False"
style="border-style:dotted;border-width:thin"
>
<Columns>
<asp:BoundField DataField="ApplicationID" HeaderText="Application ID" SortExpression="ApplicationID" Visible="True" />
<asp:TemplateField HeaderText="Application Name"><ItemTemplate><%#Eval("Application.ApplicationName")%></ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Normalized Name"><ItemTemplate><%#Eval("Application.NormalizedAppName")%></ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Notes"><ItemTemplate><%#Eval("Application.NormalizedNotes")%></ItemTemplate></asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<asp:RadioButtonList SelectedValue='<%#Eval("RequirementOption")%>' ID="rblRequirementOption" RepeatDirection="Horizontal" runat="server">
<asp:ListItem Value="Need Now" Text="Need Now"></asp:ListItem>
<asp:ListItem Value="Need Someday" Text="Need Someday"></asp:ListItem>
<asp:ListItem Value="Do Not Need" Text="Do Not Need"></asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="NormalizedNotes" HeaderText="Notes" Visible="False" />
</Columns>
</asp:GridView>
What you have should work. Are you getting an error? Here's a working example copied from my current project. I'm binding to a nullable bit field - so have a hidden list item to accept the nulls.
<asp:RadioButtonList runat="server" ID="MyRbl" SelectedValue='<%# Bind("MyRblField") %>'
CssClass="NormalTextBox" RepeatDirection="Horizontal">
<asp:ListItem Value="false" Text="No" />
<asp:ListItem Value="true" Text="Yes" />
<asp:ListItem Value="" Text="" style="display: none" />
</asp:RadioButtonList>
I also experienced this problem (nothing selected in radiobuttonlist) when binding against boolean values in MS SQL:
radDefault.Items.Add(new ListItem("Yes", "true"));
radDefault.Items.Add(new ListItem("No", "false"));
In my case, the solution was to capitalize the first letter of the true/false values, then the radiobuttonlistworked as expected:
radDefault.Items.Add(new ListItem("Yes", "True"));
radDefault.Items.Add(new ListItem("No", "False"));
Or, declaratively:
<asp:RadioButtonList runat="server" ID="radDefault" SelectedValue='<%# Bind("DB_FIELD") %>'>
<asp:ListItem Value="False" Text="No" />
<asp:ListItem Value="True" Text="Yes" />
</asp:RadioButtonList>
I didn't like the idea of using css to hide an item. Instead, I found this solution to add a blank item but remove it in the code behind.
<asp:RadioButtonList ID="MyRadioButtonList" runat="server"
SelectedValue='<%# Bind("Blah") %>'
OnDataBound="MyRadioButtonList_DataBound">
<asp:ListItem Value=""></asp:ListItem>
<asp:ListItem Value="A"></asp:ListItem>
<asp:ListItem Value="B"></asp:ListItem>
<asp:ListItem Value="C"></asp:ListItem>
</asp:RadioButtonList>
protected void MyRadioButtonList_DataBound(object sender, EventArgs e)
{
RadioButtonList list = (RadioButtonList)sender;
ListItem blank = list.Items.FindByValue("");
if (blank != null)
list.Items.Remove(blank);
}
<asp:RadioButtonList runat="server" ID="MyRbl" SelectedValue='<%# Bind("MyRblField") %>'
CssClass="NormalTextBox" RepeatDirection="Horizontal">
<asp:ListItem Value="false" Text="No" />
<asp:ListItem Value="true" Text="Yes" />
<asp:ListItem Value="" Text="" selected="true" style="display: none" />
</asp:RadioButtonList>
It work me .....
gnanasekar.s vilangulathur

Resources