Replacing a TextBox with a DropDownList in InsertItemTemplate - c#

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.

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>

Binding asp:DropDownList SelectedValue to a Boolean doesn't work - any workarounds?

Our UX team doesn't like the checkbox for handling a boolean - they want a asp:DropDownList with two options for true/false.
My bool has to be bound using <%# Bind("") %>, as it's in the edit template of a asp:GridView.
Here is my code:
<asp:GridView ...>
...
<Columns>
...
<asp:TemplateField ...>
...
<EditItemTemplate>
<asp:DropDownList ID="ExcludedDropDown" runat="server" SelectedValue='<%# Bind("IsExcluded") %>'>
<asp:ListItem Value="false" Text="Include" meta:resourcekey="ListItemResource0"></asp:ListItem>
<asp:ListItem Value="true" Text="Exclude" meta:resourcekey="ListItemResource1"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
...
</Columns>
</asp:GridView>
With a breakpoint inside the EditItemTemplate, I tried following in the immediate window:
Eval("Exclude")
false
Where "false" would be the result of the Eval. Just for good measure, I did try to change the value of my "true" item to: "True", "T", "t", "Y", "y", "-1","0", "1", ""
And all yield the same exception:
'DropDownList' has a selectedvalue which is invalid because it does not exist in the list of items.
I tried to work around using the "OnDataBinding" event, but this didn't help me at all (maybe I just did it wrong).
I prefer not to add a property to our Class that converts the bool into a string/integer (as that would work right away).
Is it impossible to bind a bool to DropDownList - and if it is, why would it make sense to have this restriction in ASP.NET? Have a hard time seeing the difference between supporting integers and boolean in DropDownList.
I changed ListItem's Value start with capital (True|False), and it works fine. You might want to give a try.
<asp:DropDownList ID="ExcludedDropDown" runat="server"
SelectedValue='<%# Bind("IsExcluded") %>'>
<asp:ListItem Value="True" Text="Include"></asp:ListItem>
<asp:ListItem Value="False" Text="Exclude"></asp:ListItem>
</asp:DropDownList>
Here is how I test
public class Something
{
public string Some { get; set; }
public bool IsExcluded { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var collections = new List<Something>
{
new Something {Some = "One", IsExcluded = true},
new Something {Some = "Two", IsExcluded = false},
};
GridView1.DataSource = collections;
GridView1.DataBind();
}
}
Thank you for the answer! Knowing the "correct" approach narrowed my search to find the actual bug. By mistake, the meta:resourcekey was mapped (by our translation tool) to handle the Value. Removing the meta:resourcekey attribute and changing to capitalized True/False solved it for me. Here is the new code with the changes applied:
<asp:GridView ...>
...
<Columns>
...
<asp:TemplateField ...>
...
<EditItemTemplate>
<asp:DropDownList ID="ExcludedDropDown" runat="server" SelectedValue='<%# Bind("IsExcluded") %>'>
<asp:ListItem Value="False" Text="Include" ></asp:ListItem>
<asp:ListItem Value="True" Text="Exclude" ></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
...
</Columns>
</asp:GridView>

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();

Drop Down List and Selected Value

I'm having a very hard time figuring out what I'm doing wrong here. In my Edit Item Template I have the following code for my drop down list:
<asp:DropDownList ID="dd_is_active" runat="server" AppendDataBoundItems="true"
DataValueField="Enabled">
<asp:ListItem Text="Yes" Value="1"></asp:ListItem>
<asp:ListItem Text="No" Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:HiddenField ID="is_activeTextBox" runat="server" Value='<%# Bind("Enabled") %>' />
Here is my aspx.cs code:
protected void ListView1_ItemInserting(object sender, ListViewInsertEventArgs e)
{
e.Values["SUB_last_modified_date"] = DateTime.Now.ToString();
e.Values["SUB_last_modified_by_user_id"] = HttpContext.Current.User.Identity.Name;
e.Values["SUB_last_modified_by_user_name"] = Session["UserName"].ToString();
e.Values["Enabled"] = ((DropDownList)(sender as ListView).InsertItem.FindControl("dd_is_active")).SelectedValue;
e.Values["Category_ID"] = ((DropDownList)(sender as ListView).InsertItem.FindControl("dd_category")).SelectedValue;
}
protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
e.NewValues["SUB_last_modified_date"] = DateTime.Now.ToString();
e.NewValues["SUB_last_modified_by_user_id"] = HttpContext.Current.User.Identity.Name;
e.NewValues["SUB_last_modified_by_user_name"] = Session["UserName"].ToString();
}
It seems something is either missing from my .cs code or I have the values of 1 and 0 bound incorrectly in the html code. This exact same code works for the Insert Item Template, but the Update (or Edit Item Template) is not working correctly.
When I try to edit an item in my table I get an error stating the input string is in an incorrect format. I know it's trying to bind the Text of "Yes" or "No" but I need to ind to the Values of either "0" or "1". Any help is greatly appreciated!
I think your syntax is wrong for HiddenField value.
Instead of this
<asp:HiddenField ID="is_activeTextBox" runat="server" Value='<%# Bind("Enabled") '>' />
It should be
<asp:HiddenField ID="is_activeTextBox" runat="server" Value='<%# Bind("Enabled")%>' />

Categories