I have an asp.net chckebox list:
<asp:EntityDataSource ID="GradeLevelEntityDataSource" runat="server"
ConnectionString="name=NewCourseRequestDataEntities"
DefaultContainerName="NewCourseRequestDataEntities" EnableFlattening="False"
EntitySetName="grade_levels" OrderBy="it.grade_level_index">
</asp:EntityDataSource>
<asp:CheckBoxList ID="GradeLevelCheckBoxList" runat="server" cssClass="horizontalcontrols"
DataSourceID="GradeLevelEntityDataSource"
DataTextField="grade_level_description" DataValueField="grade_level_id" AutoPostBack="True"
OnSelectedIndexChanged="CollegeInstitutionsListboxChange"
RepeatDirection="Horizontal" RepeatLayout="Flow">
</asp:CheckBoxList>
A user can return to the page, it gets the record ID, pulls the record data, and should check the appropriate checkboxes:
CheckBoxList grades = (CheckBoxList)FindControl("GradeLevelCheckBoxList");
foreach (request_grade_college r in CurrentRequest.request_grade_college)
{
ListItem grade = grades.Items.FindByValue(r.grade_level_id.ToString());
if (grade != null)
{
grade.Selected = true;
}
}
the portion of the code r.grade_level_id.ToString() does return the correct GUID, as type String. However, ListItem grade remain null, so none of the GradeLevelCheckboxList get checked.
What am I missing please?
I think that the data is not yet bound when you try to access it using Items.FindByValue(), try calling
grades.DataBind();
before the foreach loop.
Please make sure the listbox item's Value property has the correct value, if Item's Text and Value are different.
Also, Value Property and grade_level_id are exactly of same case and with trimmed spaces.
Related
I have a RadTextBox control in my form, and in one of the methods, it sets the text of the control as such:
SecondHalfTB.EmptyMessage = sharedMailbox.MailboxEmail.Replace("CAAS_", string.Empty)
.Replace("#caas.gov.sg", string.Empty);
<td class="ms-formbody">
CAAS_<telerik:RadTextBox ID="SecondHalfTB" runat="server" MaxLength="255">
</telerik:RadTextBox>
#caas.gov.sg
<div>
<asp:Label ID="lbSecondHalfTB" runat="server" CssClass="WarningMessage"></asp:Label>
</div>
</td>
If I did not enter any values in the textbox, will the following statement return an empty string?
string newEmail = SecondHalfTB.Text;
if (newEmail == string.Empty)
{
newEmail = SecondHalfTB.DisplayText;
}
CAAS_<telerik:RadTextBox ID="SecondHalfTB" runat="server" MaxLength="255">
</telerik:RadTextBox>
#caas.gov.sg
The values are actually hardcoded in your markup, aren't they? All you need is just remove them from the HTML.
By definition, the EmptyMessage property lets you specify the appearance of the input control when the user has not entered a value.
Whereas the DisplayText property allows you to set the display value from the Server to a different value the actual value. Similar to the empty message, but shown even if the input is not empty. This text will be cleared once the user changes the input value.
For you updated question - newEmail will be the same value as the DisplayText if the actual value of the textbox is empty.
In my C# web application, I have three textboxes, three drop down lists, and one button.
The button is suppose to run a SQL string that will take the values of whatever is in typed in the textboxes, whatever is selected, and be inserted into the database. The values inserted may not be null so I don't want any blank entries. By default, I have the DropDownList like so in the source:
<asp:DropDownList ID="ReadDrop" runat="server">
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="1">Yes</asp:ListItem>
<asp:ListItem Value="0">No</asp:ListItem>
</asp:DropDownList>
So there is a blank entry (default), and then the yes/no. There are three of these drop down lists in the application. In my C# code, I have the following to prevent the button from firing if there is a blank entry:
if (UsernameBox.Text != "" & FirstNameBox.Text != "" & LastNameBox.Text != "" /* check for blank dropdownlist? */)
My current issue is that I don't know how to check the dropdownlist for a blank entry. My guess would have been to check to see if ReadDrop.Text is blank, but I am relatively inexperienced in ASP.NET and am wondering if there is a "proper" way to do this.
Thanks!
You could use SelectedIndex > 0:
if (UsernameBox.Text != "" & FirstNameBox.Text != "" & LastNameBox.Text != "" && ReadDrop.SelectedIndex > 0)
{
// ...
}
Note that the SelectedIndex is -1 if no item is selected and yes/no have 1/2.
Another option is to use the SelectedItem:
ListItem selectedItem = ReadDrop.SelectedItem;
if(selectedItem != null && !String.IsNullOrEmpty(selectedItem.Text))
{
// ...
}
However, i think that you actually want to prevent that the user selects no item, or in other words, validate that he selects something. Then use a RequiredFieldValidator, you have to set the InitialValue to "":
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Select Something" ControlToValidate="ReadDrop"
InitialValue=""></asp:RequiredFieldValidator>
You could assign a different Value to your empty item and change the InitialValue appropriately:
I keep getting the above error in the title line and it makes no sense, because I am using a sample table with only 5 records and each record has a value as per the drop down menu.
This is my code used to declare the drop down list. I have joined two tables in my SQL data source to reflect what I want populated in the grid view and have hidden columns as necessary. I am using the same data source to populate the drop down list any help would be most appreciated
<asp:DropDownList ID="DropDownListCurrency" runat="server"
CausesValidation="True" DataSourceID="GridView"
DataTextField="Currency" DataValueField="Currency_ID"
AppendDataBoundItems="True">
<asp:ListItem Value="0" Text="<Select>" Enabled="True"></asp:ListItem>
</asp:DropDownList>
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
GridViewRow row = GridView1.SelectedRow;
AccountNumber.Text = (string)row.Cells[0].Text;
....
DropDownListCurrency.SelectedValue = (string)row.Cells[8].Text;
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
}
Attempt to find the value in the drop down list before attempting to set the SelectedValue, like this:
if (DropDownListCurrency.Items.FindByValue(row.Cells[8].Text.ToString().Trim()) != null)
{
DropDownListCurrency.SelectedValue = row.Cells[8].Text.ToString().Trim();
}
Note: The Trim() call will remove any leading or trailing spaces in your text box text, which could be a cause for a match not being found.
So your full code should be this:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
GridViewRow row = GridView1.SelectedRow;
AccountNumber.Text = (string)row.Cells[0].Text;
....
if (DropDownListCurrency.Items.FindByValue(row.Cells[8].Text.ToString().Trim()) != null)
{
DropDownListCurrency.SelectedValue = row.Cells[8].Text.ToString().Trim();
}
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
}
it's so simple just use this
Dropdown.SelectedValue = null;
Dropdown.DataBind();
Hi maybe in that cell from your gridview have white space or dropdownlist have white space for example isn't the same this
Dolar__ = Dolar
or
Dolar = Dolar__
use a Trim in code behind to clear white spaces in SQL Server don't use Rtrim this isn't good practices
Dropdownlist values are different from the values in the column of the database.
Example: The dropdown show Emma, but in the database exist Emma and Emma1.
The dropdownlist cannot find the value Emma1.
This can happen if the rows in the drop down list are in a related table and referential integrity is not being used in the database. In my case, I use referential integrity but I add a boolean to the drop down list record to say "Disabled" - i.e. I no longer want users to be able to select this value in the drop down list. So I filter the drop down list to show only values that are not "Disabled", but then the problem then is that existing data might already contain the value, leading to the error message above when Edit is pressed on the grid.
The way I handle this situation, is as follows:
Make the drop down list in question unbound to avoid the error.
Add the following code in the code behind:
protected void StaffTypeGridView_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow ||
e.Row.RowIndex != StaffTypeGridView.EditIndex) return;
var staffType = (StaffType)e.Row.DataItem;
var appCode = staffType.AppCode;
var ddl = (DropDownList) e.Row.FindControl(ddlName);
if (!string.IsNullOrEmpty(value) &&
ddl.Items.FindByValue(value) == null)
{
ddl.Items.Add(new ListItem
{
Value = value,
Text = value + " (Deleted)"
});
}
ddl.SelectedValue = value;
}
Don't forget to write code either in the DropDownList_OnSelectedIndexChanged or GridViewOnRowUpdating to update the value back into the data source (as its an unbound field).
Add a custom validator to the EditItemTemplate to ensure that data that has been deleted cannot be entered, i.e. the user MUST change the value in the drop down list in order to save.
This sounds quite complicated to explain but is quite a straightforward way of providing this functionality, unless anybody has any better ideas...
Setting Text property of DropDownList in ASPX to value missing from ItemList causes the same error.
In my case what happened was that I have added by mistake meta-resourcekey tag where Text property was set to value missing in ItemList.
The resources values were:
table {
border-collapse: collapse;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
table th, table td {
border: solid 1px darkgray;
padding: 0 5px;
}
table.tr:first(){
}
<table css="table">
<tr>
<th>Name</th>
<th>Value</th>
<th>Comment</th>
</tr>
<tr>
<td>Template.Text</td>
<td>Template</td>
<td></td>
</tr>
<tr>
<td>Template.ToolTip</td>
<td>template of standard outgoing email settings</td>
<td></td>
</tr>
</table>
and ASPX control was:
<asp:DropDownList runat="server" ID="ddlTemplate" CssClass="form-control dropdownlist" meta:resourcekey="Template" >
<asp:ListItem Selected="True" meta:resourcekey="TemplateEmpty" Value="EMPTY" />
<asp:ListItem Selected="False" meta:resourcekey="TemplatePOP3" Value="POP3" />
<asp:ListItem Selected="False" meta:resourcekey="TemplatePOP3Secured" Value="POP3S" />
<asp:ListItem Selected="False" meta:resourcekey="TemplateIMAP" Value="IMAP" />
<asp:ListItem Selected="False" meta:resourcekey="TemplateIMAPSecured" Value="IMAPS" />
</asp:DropDownList>
Removing the meta:resourcekey did the trick for me.
#region by zia for if item not exist in dropdownlist
string qlf = dsEmp.Tables["tblEmp"].Rows[0]["Group"].ToString();
ListItem selLqli = ddlGroup.Items.FindByText(qlf.Trim());
if (selLqli != null)
{
ddlGroup.ClearSelection();
}
else
{
ddlGroup.SelectedIndex = 0;
}
#endregion
I have used nvarchar(20) as datatype in db because in char datatype space comes so there was difference in text including space. Trim() can be also used.
You can use the Trim() method
ddlname.Text = dt.Rows[0][3].ToString().Trim();
This is a Dropdown control where I am binding the data, after bind I am putting the select statement. Even though the index is kept to 0 always select comes last like this:
Current output:
india
Auz
US
--select--
Required output:
--select--
india
AUZ
US
My Code
ddlcounty.DataSource = dtNew;
ddlcounty.DataTextField = "Weight";
ddlcounty.DataValueField = "Weight";
ddlcounty.DataBind();
ddlcounty.Items.Add("--Select--");
ddlcounty.SelectedValue = "0";
What is the change required here?
Thanks
You're doing your binding first.
When you get to the part where you are adding your default condition, you're actually adding to the end of the list.
Instead of :-
ddlcounty.Items.Add("--Select--");
Do :-
ddlcounty.Items.Insert(0, new ListItem("--Select--"));
This will insert your default option as the first element of Items.
Announced edit
You won't need :-
ddlcounty.SelectedValue = 0;
.. as if you don't explicitly specify, the first item in a drop down list is automatically selected.
If, however, you want to be explicit about it, you can do the following:-
ddlcounty.Items.Insert(0, new ListItem("--Select--","0"));
ddlcounty.SelectedValue = 0;
Would you please try below way:
Just set AppendDataBoundItems to true and Insert a ListItem as selected, and 'ClearSelection' before selecting item as below.
ddlcounty.AppendDataBoundItems = true;
ddlcounty.DataSource = dtNew;
ddlcounty.DataTextField = "Weight";
ddlcounty.DataValueField = "Weight";
ddlcounty.DataBind();
ddlcounty.ClearSelection();
ddlcounty.Items.Insert(0, new ListItem { Value = "0", Text = "--Select--", Selected = true });
ddlcounty.SelectedValue = "0";
You could also declare the "select one" ListItem declaratively in your aspx page like so
<asp:DropDownList ID="ddUIC" runat="server" AppendDataBoundItems="true" Width="200px" BackColor="White" Font-Size="10px" SelectedValue='<%# Bind("Weight") %>' DataTextField="Weight" DataValueField="Weight" >
<asp:ListItem Text="Select One" Value=""></asp:ListItem>
/asp:DropDownList>
But your AppendDataBoundItems would have to be set to true
And you could still perform your databinding on the backend.
I have created a ListView that has editing enabled, the wizard generated the table with the use of textboxes but i require the use of dropdown lists for some options.
I have created the dropdown list
<asp:DropDownList ID="ActionStatusTextBox" runat="server">
<asp:ListItem Value="Ongoing">Ongoing</asp:ListItem>
<asp:ListItem Value="Open">Open</asp:ListItem>
<asp:ListItem Value="Closed">Closed</asp:ListItem>
</asp:DropDownList>
The drop down list generates successfully but doesn't submit and enter itself in the databse.
<%# Bind("ActionStatus") %>'
The above snippet needs to used somewhere in order to bind the data but which parameter does it need attaching to to pass the data?
I've tried everything and its giving me a right headache!
Thanks
Did you try:
<asp:DropDownList .. SelectedValue='<%# Bind("ActionStatus") %>' />
The SelectedValue property doesn't appear, but I believe you can set it this way.
HTH.
What are you attempting to insert into the database? You shouldn't need to bind anything if you add your listitems manually. You could just
string value = ActionStatusTextBox.SelectedValue;
I had the same issue. Check out this thread: Why is employee_id not being inserted into database
The key was in adding a function:
Protected Sub AbsentListView_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewInsertEventArgs) Handles AbsentListView.ItemInserting
e.Values("employee_id") = DirectCast(AbsentListView.InsertItem.FindControl("ExcusedAbsences_employee_idDropDownList2"), DropDownList).SelectedValue
End Sub
Which basically set the value of the dropdown when it needed it, and once i did this, the value was going into the database.
protected void ContactsListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
//Verify there is an item being edited.
if (ContactsListView.EditIndex >= 0)
{
//Get the item object.
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
// Check for an item in edit mode.
if (dataItem.DisplayIndex == ContactsListView.EditIndex)
{
// Preselect the DropDownList control with the Title value
// for the current item.
// Retrieve the underlying data item. In this example
// the underlying data item is a DataRowView object.
DataRowView rowView = (DataRowView)dataItem.DataItem;
// Retrieve the Title value for the current item.
String title = rowView["Title"].ToString();
// Retrieve the DropDownList control from the current row.
DropDownList list = (DropDownList)dataItem.FindControl("TitlesList");
// Find the ListItem object in the DropDownList control with the
// title value and select the item.
ListItem item = list.Items.FindByText(title);
list.SelectedIndex = list.Items.IndexOf(item);
}
}
}