Web custom control with dropdown list - c#

I am trying to create a custom web control with a few controls on it, a textbox, label and dropdownlist, what I would like to do is add a property on the custom control to allow add select options on the dropdown list, the same way you would if it was just a normal dropdownlist i.e.
<asp:DropDownList ID="normalddl" runat="server">
<asp:ListItem Text="1st value" Value="0"></asp:ListItem>
<asp:ListItem Text="2nd value" Value="1"></asp:ListItem>
</asp:DropDownList>
I want a custom control that will look something like this (this is a simplified version)
<mycustomControl:ControlNamt ID="customddl" runat="server" >
<asp:ListItem Text="1st value" Value="0"></asp:ListItem> -- how would I go about adding this in the custom control?
<asp:ListItem Text="2nd value" Value="1"></asp:ListItem>
</mycustomControl:ControlNamt>

Not an answer you are looking for. Just a suggestion of how to achieve that by UserControls
UserControl markup:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="UC1.ascx.cs" Inherits="WebFormsScratch.UCTests.UC1" %>
<%-- Other controls here --%>
<asp:DropDownList runat="server" ID="ddl">
</asp:DropDownList>
UserControl code-behind:
public partial class UC1 : System.Web.UI.UserControl
{
public IEnumerable<ListItem> DDLData;
protected void Page_Load(object sender, EventArgs e)
{
}
public override void DataBind()
{
ddl.DataSource = DDLData;
ddl.DataBind();
base.DataBind();
}
}
aspx page using that control (mark up; bare minimum)
<%# Register Src="~/UCTests/UC1.ascx" TagPrefix="uc1" TagName="UC1" %>
...
...
<uc1:UC1 runat="server" ID="uc1" />
Code behind of aspx page using that control
protected void Page_Load(object sender, EventArgs e)
{
uc1.DDLData = new []
{
new ListItem("1st Item", "0"),
new ListItem("2nd Item", "1"),
new ListItem("3rd Item", "2"),
};
uc1.DataBind();
}

Related

CheckBoxlist Updating a dropdowlist in UpdatePanel no longer PostBack

I need to Update a Dropdowlist according to the selected value(s) in a CheckBoxList avoiding the page to reload, I am using an UpdatePanel.
The dropdwonlist should always have an AutoPostback, it should always trigger my "SearchEvent"
I used an UpdatePanel and an AsyncPostBackTrigger on my CheckBoxlist to call the function in code behind to refresh the dropdowlist.
It works only one time. After the first call, I cannot trigger the CheckBoxlist SelectedIndexChanged, instead I get the error :
"Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 404"
My dropdownlist also lose the PostBack, nothing happens.
The View ASPX :
<td>
<asp:ScriptManager ID="ScriptManager" runat="server" />
<asp:CheckBoxList ID="IsActiveFilterCheck" runat="server" AutoPostBack="true" AppendDataBoundItems="true" CausesValidation="False">
<asp:ListItem Text="Active" Value="1" />
<asp:ListItem Text="Closed" Value="0" />
</asp:CheckBoxList>
</td>
<td>
<asp:UpdatePanel ID="UpdatePanel1" ChildrenAsTriggers="true" UpdateMode="Conditional" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="IsActiveFilterCheck" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<br /><br />
<asp:DropDownList ID="StatusFilterList" runat="server" DataTextField="Name" DataValueField="Id">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
</td>
My code behind :
private void Page_Load(object sender, System.EventArgs e)
{
RegisterCallbacks();
if (!IsPostBack)
{
Initialize();
}
}
override protected void OnInit(EventArgs e)
{
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
CheckProfil();
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.SearchButton.ServerClick += new System.EventHandler(this.SearchButton_ServerClick);
this.StatusFilterList.SelectedIndexChanged += new System.EventHandler(this.SearchButton_ServerClick);
this.IsActiveFilterCheck.SelectedIndexChanged += new System.EventHandler(this.IsActiveFilterCheck_Changed);
this.Load += new System.EventHandler(this.Page_Load);
}
protected void IsActiveFilterCheck_Changed(object sender, EventArgs e)
{
// Update the Status Filter List
StatusFilterList.Items.Clear();
if (IsActiveFilterCheck.Items.Cast<ListItem>().Where(li => li.Selected).ToList().Count != 1)
{
BindListInsertAll(StatusFilterList, ExpectedStatusCollection.Instance.GetAll());
}
else
{
IList statusSelected = ExpectedStatusCollection.Instance
.GetAll().Cast<ExpectedStatusDo>()
.Where(exp => IsActiveFilterCheck.SelectedValue == "1" ? exp.Id != 5 && exp.Id != 6 : exp.Id == 5 || exp.Id == 6)
.ToList(); // Only Dead and Signed
// Update the Status
BindListInsertAll(StatusFilterList, statusSelected);
}
UpdatePanel1.Update();
//FindByFilter();
}
When I change the IsActiveFilterCheck checkboxlist I should update only the StatusFilterList as shown in the function IsActiveFilterCheck_Changed, without reloading the full page.
This StatusFilterList should always be able to call/Trigger the event SearchButton_ServerClick
Right now It works only one time when the IsActiveFilterCheck is fired my dropdowlist is updated but after when I click anywhere I get the error and I can't trigger the IsActiveFilterCheck
Take a look to this :
AsyncPostBackTrigger works only the first time
People usually recreates the trigger to work after first time.

Dynamically change radiobuttonlist name in asp.net

In my aspx file, I have a drop down list
<asp:DropDownList runat="server" ID="Dlist" CssClass="dropdown" AutoPostBack="true" SelectedIndexChanged="CtrlChanged">
<asp:ListItem Text="Select item" Value="1"></asp:ListItem>
</asp:DropDownList>
I have a radio button list
<asp:RadioButtonList ID="RadioButtonList1" RepeatColumns="1"
RepeatDirection="Vertical" RepeatLayout="Table" runat="server" AutoPostBack="true">
<asp:ListItem>Option 1</asp:ListItem>
<asp:ListItem>Option 2</asp:ListItem>
</asp:RadioButtonList>
Now I want to change the name of one or both of the radio buttons in the radio button list after something has been selected from the dropdown list using C#. Below is my attempt but not working.
protected void CtrlChanged(Object sender, EventArgs e) {
//attempting to change text of first radio button when item has been selected from dropdownlist
RadioButtonList1.SelectedIndex = 0;
RadioButtonList1.SelectedItem.Text = "Text changed!";
}
First, it is OnSelectedIndexChanged, not SelectedIndexChanged. And the ListItems of a RadioButtonList are index based, so you need to access them like this:
protected void CtrlChanged(object sender, EventArgs e)
{
RadioButtonList1.Items[0].Text = "NewValue 1";
RadioButtonList1.Items[1].Text = "NewValue 2";
}
Your way does change the text, but only for the item you set the SelectedIndex of. And it will change the selected radiobutton to the first one, should one already have been selected.

get value of ddl, txtbox, calendar used in user control on main page using findcontrol in asp.net c#?

I want to do a task in which i want that using findControl during the use of webusercontrol on web form to get value of webusercontrol on main page I mean, I've created a webusercontrol and have used on web form. In webusercontrol.ascx page i use a textbox, calendar, and dropdownlist. Now I want to get value(which i choose from txtbox, ddl etc) should be display on main page. I mean, I want to use a button on default.aspx page and in a variable want to store value of txtbox, calendar etc. and using a FindControl want to get these values on main page. How I can do this plz help me by code plz I'm new in programing.
This is the code of ascx page
<%# Control Language="C#" ClassName="CalendarUserControl" %>
<asp:TextBox ID="txtData" runat="server"></asp:TextBox> <br />
<asp:Calendar ID="Calendar1" runat="server" BackColor="Beige" >
</asp:Calendar>
<br/>
<asp:DropDownList ID="ddlthings" runat="server">
<asp:ListItem> Apple</asp:ListItem>
<asp:ListItem> Banana</asp:ListItem>
<asp:ListItem> Mango</asp:ListItem>
<asp:ListItem> Grapes</asp:ListItem>
</asp:DropDownList>
default.aspx page
<div>
<uc1:CalendarUserControl ID="CalendarUserControl1" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" OnClick="btn_Click" Text="Button" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
Define properties in your user control, that will return values of controls you want. For example
public partial class CalendarUserControl: UserControl
{
// this is code-behind of your user control
public string Data
{
get {return txtData.Text;}
}
public DateTime CalendarDate
{
get {return Calendar1.SelectedDate;}
}
// same approach for drop down list ddlthings
}
Then in your aspx page, just read those values, for example in your btn_Click event handler
protected void btn_Click(object sender, EventArgs e)
{
var textBoxValue = CalendarUserControl1.Data;
var calendarValue = CalendarUserControl1.CalendarDate;
//....
}
i did it, just write these lines in default.cs
protected void btn_Click(object sender, EventArgs e)
{
TextBox myLabel = (TextBox)CalendarUserControl1.FindControl("txtData");
string x = myLabel.Text.ToString();
Calendar c = (Calendar)CalendarUserControl1.FindControl("Calendar1");
string date = c.SelectedDate.ToString();
DropDownList b = (DropDownList)CalendarUserControl1.FindControl("ddlthings");
string ddl = b.SelectedValue;
Label1.Text = "Your text is: " + x + "<br />"+ " Your Selected Date is: " + date + "<br />"+ " Your Selected Item is: " + ddl;
}

How to load items into dropdownlist after selecting item from another dropdownlist in asp.net c#

I have four dropdownlistbox in my form, i want to load items into three dropdownlists according to the selection of items from the first drop down list , my first dropdown list has folloding items
Amount ,
PAC ,
Base UOM
Whatever i am selecting from first drop down list , i want to load the same selected item into remaining three dropdownlist
I have tried the following code but it is not working as expected
protected void ddl_UOM_SelectedIndexChanged(object sender, EventArgs e)
{
string uom_Name = ddl_UOM.SelectedItem.Value;
ddl_UOM2.Items.Add(uom_Name);
ddl_UOM3.Items.Add(uom_Name);
ddl_UOM4.Items.Add(uom_Name);
}
pls help.
You need to use Ajax Control Tool kit's Cascaded Drop-down
Here is the like for it:
http://www.asp.net/AjaxLibrary/AjaxControlToolkitSampleSite/Walkthrough/CCDWithDB.aspx
and here is the demo:
http://www.asp.net/AjaxLibrary/AjaxControlToolkitSampleSite/CascadingDropDown/CascadingDropDown.aspx
here is a tutorial link:
http://www.dotnetfox.com/articles/ajax-cascading-dropdown-example-with-database-in-Asp-Net-1078.aspx
Hope this material helps.
May be you don't have set AutoPostBack property to true. Try below code sample :
ASPX:
<asp:DropDownList runat="server" ID="parentDropDown" OnSelectedIndexChanged="parentDropDown_SelectedIndexChanged" AutoPostBack="true">
<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>
<asp:DropDownList runat="server" ID="child1">
</asp:DropDownList>
<asp:DropDownList runat="server" ID="child2">
</asp:DropDownList>
Code Behind:
protected void parentDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
string uom_Name = parentDropDown.SelectedValue;
child1.Items.Add(uom_Name);
child2.Items.Add(uom_Name);
}
If you want to remove existing item from child before you add then:
protected void parentDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
string uom_Name = parentDropDown.SelectedValue;
child1.Items.Clear();
child2.Items.Clear();
child1.Items.Add(uom_Name);
child2.Items.Add(uom_Name);
}
You have to set AutoPostBack="true" to the first drop down list and clear other drop downs items before adding new item.
ASPX:
<asp:DropDownList ID="ddl_UOM" runat="server" OnSelectedIndexChanged="ddl_UOM_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="Amount" Value="Amount"></asp:ListItem>
<asp:ListItem Text="PAC" Value="PAC"></asp:ListItem>
<asp:ListItem Text="Base" Value="Base"></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddl_UOM2" runat="server"></asp:DropDownList>
<asp:DropDownList ID="ddl_UOM3" runat="server"></asp:DropDownList>
<asp:DropDownList ID="ddl_UOM4" runat="server"></asp:DropDownList>
ASPX.CS
protected void ddl_UOM_SelectedIndexChanged(object sender, EventArgs e)
{
string uom_Name = ddl_UOM.SelectedItem.Value;
ddl_UOM2.Items.Clear();
ddl_UOM2.Items.Add(new ListItem(uom_Name, uom_Name));
ddl_UOM3.Items.Clear();
ddl_UOM3.Items.Add(new ListItem(uom_Name, uom_Name));
ddl_UOM4.Items.Clear();
ddl_UOM4.Items.Add(new ListItem(uom_Name, uom_Name));
}
protected void ddl_UOM_SelectedIndexChanged(object sender, EventArgs e)
{
string uom_Name = ddl_UOM.SelectedItem.Value;
ddl_UOM2.Items.Clear();
ddl_UOM3.Items.Clear();
ddl_UOM4.Items.Clear();
ddl_UOM2.Items.Add(uom_Name);
ddl_UOM3.Items.Add(uom_Name);
ddl_UOM4.Items.Add(uom_Name);
}
After writing code in ddl_UOM_SelectedIndexChanged() , call ddl_UOM_SelectedIndexChanged() method from Page_Load()
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
ddl_UOM_SelectedIndexChanged(sender, e );
}
}
catch (Exception)
{
throw;
}
}
You should try to use PageMethods in JS to load the dropdowns any way you like any time you like.

Dropdown add default name

I have a dropdown it contain all country names.The code is working fine but I need to add a default choice in the dropdown.How to add a default choice?(<--choose-->).
my code is
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ddlCountryofOrgin.ascx.cs" Inherits="UserControls_DataType_ddlCountryofOrgin" %>
<asp:DropDownList ID="ddlCountry" CssClass="ddlCountry" runat="server" DataValueField="english_name"
DataSourceID="sqlCountry" OnPreRender="ddlCountry_PreRender" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged" />
<asp:SqlDataSource ID="sqlCountry" runat="server" SelectCommand="SELECT [country_id],[english_name], danish_name FROM [dbo].[nano_country] WHERE [is_active] = 1 ORDER BY [sort_order] DESC, [english_name] ASC" />
Thanks in advance for help...
Set AppendDataBoundItems as True
and add item to dropdownlist:
<asp:ListItem Selected="True" Value="0">--Choose--</asp:ListItem>
Code:
<asp:DropDownList ID="ddlCountry" CssClass="ddlCountry" runat="server" AppendDataBoundItems = "True" DataValueField="english_name"
DataSourceID="sqlCountry" OnPreRender="ddlCountry_PreRender" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged" >
<asp:ListItem Selected="True" Value="0">--Choose--</asp:ListItem>
</asp:DropDownList >
protected void Page_Load(object sender, system.EventArgs as e)
{
ddlCountry.Items.Insert(0,"--Choose--");
}
Try this code
ddlCountry.Items.Insert(0, new ListItem("Select","--Choose--")

Categories

Resources