Cant set and get value using dropdown list - asp.net

This dropdown list is inside a gird view:
<asp:TemplateField HeaderText="Test">
<ItemTemplate>
<asp:DropDownList ID="Hello" runat="server" SelectedValue='<%# Eval("beta") %>'>
<asp:ListItem Value="" Text="-">-</asp:ListItem>
<asp:ListItem Value="0" Text="0">0</asp:ListItem>
<asp:ListItem Value="1" Text="1">1</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
Every time it has to load the page containing this gridview I get exception:
{"'beta' has a SelectedValue which is invalid because it does not exist in the list of items.\r\nParameter name: value"}
The value of beta is null, however,
<asp:ListItem Value="null" Text="null">null</asp:ListItem>
Doesnt work... Note beta comes from database as the next possible values: null, 0 or 1 .Also tried getting the values from another dropdown list but doesnt work, i tried this:
GridViewRow row = GridView1.Rows[i]; //this is inside a for loop
var ddl = row.Cells[8].Controls[0] as DropDownList;
string test= ddl.SelectedIndex;
I allways get ddl as null when debugging.
So the questions are:
1. How to load the dropdown with 3 values one of them beeing null?
2. How to read the selected dropdown value without using any events like onchange or whatever, example:
CheckBox chk = row.Cells[0].Controls[0] as CheckBox;
bool isChecked = chk.Checked;

To answer you quetsions:
You can't set null as a value for a ListItem, because null is not a string literal. null means that the value is missing. null itself is "not a value". So you will need to handle that in your code:
drpList.SelectedValue = dbObj.FieldValue ?? "(n/a)";
I'm not sure what you are asking here. I would suggest using FindControl instead of using indices to access your controls.

As for your problem, Refer below article for dropdownlist in asp.net
http://www.laptrinhdotnet.com/2015/07/su-dung-control-dropdownlist-trong.html

Related

How to bind SelectedValue of DropdownList to DataSoruce when drop down is populated programmatically?

I have a GridView. When I go into edit mode on a row, I want one of the columns to be a dropdown. My first draft included this:
<asp:TemplateField HeaderText="Type">
<ItemTemplate>
<%# Eval("type_name") %>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ctlItemType" runat="server" datasourceid="dsItemTypes"
DataTextField="name" DataValueField="id"
selectedvalue='<%# Bind("item_type_id") %>' />
</EditItemTemplate>
</asp:TemplateField>
I should clarify that my data source included "type_name" as the name of the type and "item_type_id" as the ID corresponding to that name. That worked great. Cool.
But I need to restrict the values appearing in the drop down depending on other data about the record. So okay, fine, I removed the datasourceid, and instead populated the dropdown with code:
Private Sub ItemsGridView_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Handles ItemsGridView.RowDataBound
If e.Row.RowState = DataControlRowState.Edit Then
Dim ctlItemType As DropDownList = e.Row.FindControl("ctlItemType")
Dim parent_id = ItemsGridView.DataKeys(e.Row.RowIndex).Values(1)
ctlItemType.DataSource = ItemTypeActions.List(parent_id)
ctlItemType.DataBind()
End If
End Sub
That blows up with a "SelectedValue not found" error, I presume because it's trying to set the selected value before I populate the values.
So I tried setting the SelectedValue in code also. After the DataBind above I added:
ctlItemType.SelectedValue = DataBinder.Eval(e.Row.DataItem, "item_type_id")
That displays fine when I go into edit mode, but when I click "Update", it blows up, because item_type_id doesn't get included in the list of parameters passed to the update function. Because it's not Bind'ed, it's just set with an Eval.
So how do I make this work? Is there a way to bind a control to a datasource with code? I could find anything like DataBinder.Eval that is equivalent to <%# bind("whatever") %>. Or ... what?

RadDatePicker in ASP.NET Gridview TemplateField

I've got a date picker field declared within a template field in a GridView as follows:
<asp:TemplateField HeaderText="Shipping Date">
<ItemTemplate>
<asp:Label ID="lblShippingDate" runat="server" CssClass="dnnFormLabel"
AssociatedControlID="ShippingDatePicker" />
<dnn:DnnDatePicker runat="server" ID="ShippingDatePicker" />
</ItemTemplate>
</asp:TemplateField>
I can select the date just fine and it appears in my label control - I then click on a standard asp:Button which finds the selected row and despite it finding all the other controls on the row including the label control displaying the selected date, the label's Text attribute is blank:
var txtShippingDate = row.Cells[7].FindControl("lblShippingDate") as Label;
Please note that I'm using the DotNetNuke dnn:DnnDatePicker control but this is actually a RadDatePicker under the covers.
Can anyone suggest how I can successfully read the value?
Thanks for looking :)
Try following after you find label:
if(txtShippingDate != null) {
string date = Request.Form[txtShippingDate.UniqueID].ToString();
}

Changing WebControl ID Inside of a Repeater

<ItemTemplate>
<asp:Label runat="server"><%#DataBinder.Eval(Container.DataItem, "Question")%></asp:Label>
<asp:DropDownList runat="server" id="<%#DataBinder.Eval(Container.DataItem, "QuestionID")%>">>
<asp:ListItem value="1" text="Yes" />
<asp:ListItem value="0" text="No" />
</asp:DropDownList>
<ItemTemplate>
This is roughly what I'm trying to do. Obviously, the implementation is faulty, but I can't find any information on how I'd go about this in practice. Any help is appreciated.
Edit: What I'm trying to do exactly is add a DropDownList for each item in this Repeater, and upon submission of the form, use the ID's of each Yes/No answer to input into a database. The SqlDataReader that I'm using has two fields: The question content and the questionID.
I think you'd be better off using the built in support for IDs inside a Repeater. If the goal is to assign it an ID to make it easy to find the proper control after the data has been bound you might try something like this:
<asp:Repeater ID="Repeater1" runat="server>
<ItemTemplate>
<asp:Label ID="QuestionID" Visible="False" Runat="server"><%#DataBinder.Eval(Container.DataItem, "FieldContent")%></asp:Label>
<asp:DropDownList ID="MyDropDownList" Runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:Repeater>
Then, in your code you can loop through the items in the Repeater until you find the label you're looking for:
foreach (RepeaterItem curItem in Repeater1.Items)
{
// Due to the way a Repeater works, these two controls are linked together. The questionID
// label that is found is in the same RepeaterItem as the DropDownList (and any other controls
// you might find using curRow.FindControl)
var questionID = curRow.FindControl("QuestionID") as Label;
var myDropDownList = curRow.FindControl("MyDropDownList") as DropDownList;
}
A Repeater basically consists of a collection of RepeaterItems. The RepeaterItems are specified using the ItemTemplate tag. Each RepeaterItem has its own set of controls that are, by the very nature of a Repeater, associated with each other.
Say you're pulling the Repeater data from a database. Each Repeater item represents data from an individual row in the query results. So if you assign the QuestionID to a label and the QuestionName to a DropDownList, the ID in the label would match up with the name in drop down.
Could you remove the control from the markup file, and hook the repeater's onItemDataBound event. In that event, you should be able to create the dropdown control "manually", assigning whatever ID you want.

How to find checked RadioButton inside Repeater Item?

I have a Repeater control on ASPX-page defined like this:
<asp:Repeater ID="answerVariantRepeater" runat="server"
onitemdatabound="answerVariantRepeater_ItemDataBound">
<ItemTemplate>
<asp:RadioButton ID="answerVariantRadioButton" runat="server"
GroupName="answerVariants"
Text='<%# DataBinder.Eval(Container.DataItem, "Text")%>'"/>
</ItemTemplate>
</asp:Repeater>
To allow select only one radio button in time I have used a trick form this article.
But now when form is submitted I want to determine which radio button is checked.
I could do this:
RadioButton checkedButton = null;
foreach (RepeaterItem item in answerVariantRepeater.Items)
{
RadioButton control=(RadioButton)item.FindControl("answerVariantRadioButton");
if (control.Checked)
{
checkedButton = control;
break;
}
}
but hope it could be done somehow simplier (maybe via LINQ to objects).
You could always use Request.Form to get the submitted radio button:
var value = Request.Form["answerVariants"];
I think the submitted value defaults to the id of the <asp:RadioButton /> that was selected, but you can always add a value attribute - even though it's not officially an <asp:RadioButton /> property - and this will then be the submitted value:
<asp:RadioButton ID="answerVariantRadioButton" runat="server"
GroupName="answerVariants"
Text='<%# DataBinder.Eval(Container.DataItem, "Text")%>'"
value='<%# DataBinder.Eval(Container.DataItem, "SomethingToUseAsTheValue")%>' />
Since You are using javascript already to handle the radio button click event on the client, you could update a hidden field with the selected value at the same time.
Your server code would then just access the selected value from the hidden field.
I'm pretty sure that the only thing you could use LINQ to Objects for here would be to take the conditions from within the foreach loop and move them to a where clause.
RadioButton checked =
(from item in answerVariantRepeater.Items
let radioButton = (RadioButton)item.FindControl("answerVariantRadioButton")
where radioButton.Checked
select radioButton).FirstOrDefault();

Databound drop down list - initial value

How do I set the initial value of a databound drop down list in ASP.NET?
For instance, I want the values, but the first value to display should be -- Select One ---, with a null value.
I think what you want to do is this:
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="--Select One--" Value="" />
</asp:DropDownList>
Make sure the 'AppendDataBoundItems' is set to true or else you will clear the '--Select One--' list item when you bind your data.
If you have the 'AutoPostBack' property of the drop down list set to true you will have to also set the 'CausesValidation' property to true then use a 'RequiredFieldValidator' to make sure the '--Select One--' option doesn't cause a postback.
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="DropDownList1"></asp:RequiredFieldValidator>
I know this is old, but a combination of these ideas leads to a very elegant solution:
Keep all the default property settings for the DropDownList (AppendDataBoundItems=false, Items empty). Then handle the DataBound event like this:
protected void dropdown_DataBound(object sender, EventArgs e)
{
DropDownList list = sender as DropDownList;
if (list != null)
list.Items.Insert(0, "--Select One--");
}
The icing on the cake is that this one handler can be shared by any number of DropDownList objects, or even put into a general-purpose utility library for all your projects.
What I do is set the text property of the drop down list AFTER I databind it. Something like this:
protected void LoadPersonComboBox()
{
var p = new PeopleBLL();
rcmbboxEditPerson.DataSource = p.GetPeople();
rcmbboxEditPerson.DataBind();
rcmbboxEditPerson.Text = "Please select an existing person to edit...";
}
This makes the initial visible value of this dropdown show up, but not actually be a part of the drop down, nor is it a selectable.
I know this already has a chosen answer - but I wanted to toss in my two cents.
I have a databound dropdown list:
<asp:DropDownList
id="country"
runat="server"
CssClass="selectOne"
DataSourceID="country_code"
DataTextField="Name"
DataValueField="CountryCode_PK"
></asp:DropDownList>
<asp:SqlDataSource
id="country_code"
runat="server"
ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
SelectCommand="SELECT CountryCode_PK, CountryCode_PK + ' - ' + Name AS N'Name' FROM TBL_Country ORDER BY CountryCode_PK"
></asp:SqlDataSource>
In the codebehind, I have this - (which selects United States by default):
if (this.IsPostBack)
{
//handle posted data
}
else
{
country.SelectedValue = "US";
}
The page initially loads based on the 'US' value rather than trying to worry about a selectedIndex (what if another item is added into the data table - I don't want to have to re-code)
To select a value from the dropdown use the index like this:
if we have the
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true"></asp:DropDownList>
you would use :
DropDownList1.Items[DropDownList1.SelectedIndex].Value
this would return the value for the selected index.
hi friend in this case you can use the
AppendDataBound="true"
and after this use the list item.
for e.g.:
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="--Select One--" Value="" />
</asp:DropDownList>
but the problem in this is after second time select data are append with old data.
Add an item and set its "Selected" property to true, you will probably want to set "appenddatabounditems" property to true also so your initial value isn't deleted when databound.
If you are talking about setting an initial value that is in your databound items then hook into your ondatabound event and set which index you want to selected=true you will want to wrap it in "if not page.isPostBack then ...." though
Protected Sub DepartmentDropDownList_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles DepartmentDropDownList.DataBound
If Not Page.IsPostBack Then
DepartmentDropDownList.SelectedValue = "somevalue"
End If
End Sub
dropdownlist.Items.Insert(0, new Listitem("--Select One--", "0");

Resources