How to bind to a custom property in my entity partial class - c#

I have an entity class with a MailingState property. I want to do some manipulation of that value in another property, so I added:
public string MailingStateAbbreviation
{
get { return getStateAbbreviation(MailingState); }
set { MailingState = value; }
}
However, in a DetailsView EditItemTemplate, the following fails when I try to submit the edit form:
<asp:DropDownList ID="ddlMailingState" runat="server" DataSourceID="ddlAllStates"
AppendDataBoundItems="True" DataTextField="StateAbbreviation"
DataValueField="StateAbbreviation"
SelectedValue='<%# Bind("MailingStateAbbreviation") %>'>
<asp:ListItem Value="" Text="" />
</asp:DropDownList>
I get this error:
A property named 'MailingStateAbbreviation' was not found on the entity during an insert, update, or delete operation. Check to ensure that properties specified as binding expressions are available to the data source.
If I change Bind to Eval on the SelectedValue, the form submits fine but the MailingState property is not updated. How can I bind form controls to custom properties on my entity?

Though I would prefer a more declarative approach that doesn't involve handling events, this worked. I added an OnItemUpdating handler to the DetailsView, implemented as follows:
protected void dvOrg_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
var view = (DetailsView)sender;
var mailStateDdl = (DropDownList)view.FindControl("ddlMailingState");
e.NewValues["MailingState"] = mailStateDdl.SelectedValue;
}
In my .aspx, I had this:
<asp:DropDownList ID="ddlMailingState" runat="server" DataSourceID="ddlAllStates"
AppendDataBoundItems="True" DataTextField="StateAbbreviation"
DataValueField="StateAbbreviation"
SelectedValue='<%# Eval("MailingStateAbbreviation") %>'>
<asp:ListItem Value="" Text="" />
</asp:DropDownList>

Related

My panel fails to show if the user clicks a specific drop down list item

I am attempting to get a <div> to appear when a specific ListItem is selected.
In my code behind I have:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (reportedBefore.SelectedItem.Text=="yes")
{
reportedBeforePanel.Visible = true;
}
else
{
reportedBeforePanel.Visible = false;
}
}
I referred to this article here initially, which stated I needed a few things:
You need to Enable the AutoPostBack of the dropdownlist for raising the OnSelectedIndexChanged event on server side.
AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged
Admittedly, I did not have an AutoPostBack before. After adding it, I am afraid for some reason the requested div still does not show.
<asp:DropDownList ID="reportedBefore" CssClass="larger-drop-2" AutoPostBack="true" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Text="Select" Value="Select"></asp:ListItem>
<asp:ListItem Text="No" Value="No"></asp:ListItem>
<asp:ListItem Text="Yes" Value="Yes"></asp:ListItem>
<asp:ListItem Text="Unsure" Value="Unsure"></asp:ListItem>
</asp:DropDownList>
<asp:Panel ID="reportedBeforePanel" runat="server" Visible="false">
<div id="showDiv">
<label for="yesDetails">
Please provide details
</label>
<asp:TextBox ID="yesDetails" CssClass="third-w-form" runat="server"/>
</div>
</asp:Panel>
Would someone be so kind to help me out here?
The problem is in the following if-condition:
reportedBefore.SelectedItem.Text=="yes"
By this, you are doing a case-sensitive string comparison (this is the default in .NET), but the values in your dropdownlist are written in a different way ("Yes" vs. "yes").
In order to fix this, either perform a case-insensitive string comparison
string.Compare(reportedBefore.SelectedItem.Text, "yes", true) == 0
or change the casing in the if-statement.
C# is case sensitive, so it's "Yes" not "yes":
reportedBeforePanel.Visible = reportedBefore.SelectedItem.Text == "Yes";
Alternatievely you can use this:
reportedBeforePanel.Visible = reportedBefore.SelectedItem.Text.Equals("yes", StringComparison.InvariantCultureIgnoreCase);

asp:label change visibility after hiding it

I've got an asp:Label and a asp:DropDownList that I want to be able to switch back and forth between visible and invisible when clicking on some buttons. Right now, my code looks like
aspx file
<asp:Label AssociatedControlID="statusFilter" id="statusFilterLabel" runat="server" CssClass="filterLabel">Status
<asp:DropDownList ID="statusFilter" runat="server" CssClass="filterInput" AutoPostBack="true" OnSelectedIndexChanged="anyFilter_SelectedIndexChanged" AppendDataBoundItems="True">
<asp:ListItem Selected="True" Value=" 0"><All></asp:ListItem>
</asp:DropDownList>
</asp:Label>
<asp:Button Text="ALL" ID="AllTabButton" CssClass="tabButton" runat="server" OnClick="AllTab_Click" />
<asp:Button Text="Arrived" ID="ArrivedTabButton" CssClass="tabButton" runat="server" OnClick="ArrivedTab_Click" />
code behind
protected void AllTab_Click(object sender, EventArgs e)
{
AllTabButton.CssClass = "tabButtonClicked";
ArrivedTabButton.CssClass = "tabButton";
statusFilter.Visible = true;
statusFilterLabel.Visible = true;
}
protected void ArrivedTab_Click(object sender, EventArgs e)
{
AllTabButton.CssClass = "tabButton";
ArrivedTabButton.CssClass = "tabButtonClicked";
statusFilter.Visible = false;
statusFilterLabel.Visible = false;
}
The only problem is that if I try to set Visible=true after setting Visible=false it would give me an error Unable to find control with id 'statusFilter' that is associated with the Label 'statusFilterLabel'.
I tried doing some other things instead of using Visible, like setting the style: statusFilter.Style.Add("display", "block") and setting the cssclass: statusFilter.CssClass = "displayBlock"but the resulting error always showed up.
An asp:Panel would work, but I'm avoiding using that because I want my asp:Label and asp:DropDownList to line up with several other labels and dropdownlists; putting in a panel would make them not line up properly.
I'm guessing there is something I'm missing, something I just don't get, but I can't seem to figure out what that is. If anybody has any clue as to what's happening, I would really appreciate the help!
It's not able to always find the control on postback because it's a child of statusFilter. Move the input field outside of the label:
<asp:Label AssociatedControlID="statusFilter" id="statusFilterLabel" runat="server" CssClass="filterLabel">Status
</asp:Label>
<asp:DropDownList ID="statusFilter" runat="server" CssClass="filterInput" AutoPostBack="true" OnSelectedIndexChanged="anyFilter_SelectedIndexChanged" AppendDataBoundItems="True">
<asp:ListItem Selected="True" Value=" 0"><All></asp:ListItem>
</asp:DropDownList>

Dropdown list value not displaying

hi i have gridview that when a row is selected, it populates into textboxes that are used to populate the gridview itself. the last field is a dropdownlist and its not displaying when the gridview is clicked. i set a breakpoint and see that its stuck on the first - 0 index. i dont know why it isnt moving forward... here is the code:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
....
if (DropDownListCurrency.Items.FindByValue(row.Cells[7].Text.ToString().Trim) != null)
{
DropDownListCurrency.SelectedValue = row.Cells[7].Text.ToString().Trim();
}
....
}
<asp:DropDownList ID="DropDownListCurrency" runat="server"
CausesValidation="True"
DataSourceID="CurrencyDropDownListDataSource"
DataTextField="Currency" DataValueField="Currency_ID"
AppendDataBoundItems="True">
<asp:ListItem Value="0" Text="<Select>" Enabled="True" Selected="False"></asp:ListItem>
</asp:DropDownList>
why you want take the value from textbox. Will better use DataKeyNames like this inside that event
GridViewRow row = GridView.SelectedRow;
int id = Convert.ToInt32(GridView.DataKeys[row.RowIndex].Value);
this work if you have only one value in DataKeyName if you look not there a index if you want have more than one value use this
int id = Convert.ToInt32(GridView.DataKeys[row.RowIndex].Values["FirstValue"]);
string name = Convert.ToString(GridView.DataKeys[row.RowIndex].Values["SecondValue"]);
Does the DropDownList contains the words that you wanna show displayed?
You need to set the AutoPostBack property to True:
it should be :
<asp:DropDownList ID="DropDownListCurrency" AutoPostBack="True" runat="server"
CausesValidation="True"
DataSourceID="CurrencyDropDownListDataSource"
DataTextField="Currency" DataValueField="Currency_ID"
AppendDataBoundItems="True">
<asp:ListItem Value="0" Text="<Select>" Enabled="True" Selected="False"></asp:ListItem>
</asp:DropDownList>
made a simple error...
called the wrong field was supposed to be value (Currency_ID) and not the text (Currency)
DropDownListCurrency.SelectedValue = GridView1.DataKeys[row.RowIndex].Values["Currency_ID"].ToString().Trim();

Replacing a TextBox with a DropDownList in InsertItemTemplate

I thought this would be easy and straightforward, but I seem to be having an issue with it.
Basically, I have this in a formview:
<asp:TextBox ID="StatusTextBox" runat="server" Text='<%# Bind("Status") %>' />
And I want to replace it with this:
<asp:DropDownList ID="StatusDropdown" runat="server">
<asp:ListItem Selected="True" Value="A">Active</asp:ListItem>
<asp:ListItem Value="I">Inactive</asp:ListItem>
</asp:DropDownList>
I'm not exactly sure how to bind this like the Textbox is bound.
Is there a straightforward answer?
Codebehind is not a hack, actually it's best practise since you have full control and compiler support (shows errors at compile time and avoids careless mistakes)
For example (assuming that the DropDownList is in the EditItemTemplate):
private void FormView1_DataBound(object sender, System.EventArgs e)
{
switch (FormView1.CurrentMode)
{
case FormViewMode.ReadOnly:
break;
case FormViewMode.Edit:
// note that the DataSource might be a different type
DataRowView drv = (DataRowView)FormView1.DataSource;
DropDownList StatusDropdown = (DropDownList)FormView1.FindControl("StatusDropdown");
// you can also add the ListItems programmatcially via Items.Add
StatusDropdown.DataSource = getAllStatus(); // a sample method that returns the datasource
StatusDropdown.DataTextField = "Status";
StatusDropdown.DataValueField = "StatusID";
StatusDropdown.DataBind();
StatusDropdown.SelectedValue = drv["StatusID"].ToString();
break;
case FormViewMode.Insert:
break;
}
}
Bind it to the SelectedValue property as so:
<asp:DropDownList ID="StatusDropdown" runat="server" SelectedValue='<%# Bind("Status") %>'>
The value in status has to match the value of a drop down list item.

Populate asp:dropdownlist - VS 2008

I have form with 2 DDL named
State and City
State:
<asp:UpdatePanel ID="States" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="States"EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<asp:DropDownList ID="States" runat="server"
AutoPostBack="True" DataSourceID="StatesObjectDataSource"
AppendDataBoundItems="true"
onselectedindexchanged="States_SelectedIndexChanged">
<asp:ListItem Value="-1" Text="- None -"/>
</asp:DropDownList>
<asp:ObjectDataSource ID="StatesObjectDataSource" runat="server"
onselecting="StatesObjectDataSource_Selecting"
SelectMethod="GetStates"
TypeName="Something">
</asp:ObjectDataSource>
</ContentTemplate>
</asp:UpdatePanel>
City:
<asp:DropDownList ID="Cities" runat="server">
</asp:DropDownList>
When they choose a state I want to populate the Cities DDL with all the cities for that state.
In code behind I am able to get to
States_SelectedIndexChanged(object sender, EventArgs e)
and i try to populate the Cities DDL by this
Cities.Items.Add(new ListItem(city,city));
However, I do not see my Cities DDL populated
I recommend creating a private property in the ViewState that holds the collection of physical objects. Then add the object to that list then databind the list of objects to the drop down.
Page Behind
<asp:DropDownList runat="server" ID="ddlCity" DataValueField="Key" DataTextField="Value">
</asp:DropDownList>
Code Behind
private List<KeyValuePair<string, string>> ListData
{
get { return (List<KeyValuePair<string, string>>) (ViewState["ListData"] ??
(ViewState["ListData"] = new List<KeyValuePair<string, string>>())); }
set { ViewState["ListData"] = value; }
}
protected void States_SelectedIndexChanged_SelectedIndexChanged(object sender, EventArgs e)
{
ListData.Add(new KeyValuePair<string, string>(ddlCitys.SelectedValue, ddlCitys.SelectedValue));
ddlCitys.DataSource = ListData;
ddlCitys.DataBind();
}
The get statement also employs lazy loading on the ListData property so you will never encounter a null reference exception when accessing the list.
If at all possible, I would suggest using the CascadingDropDown Extender instead of the UpdatePanel. There's no use reinventing that wheel, and the Toolkit control uses web services instead of partial postbacks (much faster).
Place your city DropDownList inside the update panel.

Categories