Dynamic change dropdownlist and textbox by custom control - c#

I want to write a custom control involving a DropDownList and a TextBox.
Actually, I want to dynamically render DropDownList and TextBox.
For example: when a user clicks a Checkbox, the Textbox will change to a DropdownList. On the other hand, when a user deselects the Checkbox, the Dropdownlist will change to a Textbox.
I know this can be done using two controls, which sets the visibility for both control. But can I do it on a custom control?

If you still want to go with that approach, here is your code.
In Design File:-
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True"
oncheckedchanged="CheckBox1_CheckedChanged" />
<div id ="control" runat="server">
</div>
In Code Behind File:-
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TextBox txt = new TextBox();
txt.ID = "txt";
control.Controls.Add(txt);
}
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked)
{
for (int ix = this.Controls.Count - 1; ix >= 0; ix--)
if (this.Controls[ix] is TextBox) this.Controls[ix].Dispose();
DropDownList ddl = new DropDownList();
ddl.ID = "ddl";
control.Controls.Add(ddl);
}
else
{
for (int ix = this.Controls.Count - 1; ix >= 0; ix--)
if (this.Controls[ix] is DropDownList) this.Controls[ix].Dispose();
TextBox txt = new TextBox();
txt.ID = "txt";
control.Controls.Add(txt);
}
}
Hope this is what you were looking for.

You could try this code
ASPX
<%# Control Language="C#" AutoEventWireup="true" CodeFile="dynamicControl.ascx.cs" Inherits="dynamicControl" %>
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true"
oncheckedchanged="CheckBox1_CheckedChanged" />
<asp:DropDownList ID="DropDownList1" runat="server" visible="false">
</asp:DropDownList>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
CodeBehind
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
DropDownList1.Visible = CheckBox1.Checked;
TextBox1.Visible = !CheckBox1.Checked;
}
This snippet will show a dropDownList if CheckBox is checked and change to TextBox if it's not checked. Despite this is possible I don't think this is the right approach. (eg: AutoPostBack needed, set visibility...)
What do you try to achieve?

Related

C# Repeater focusing the first element after DataSource is changed

I have a Repeater with a certain DataSource (consisting of a list of images). The Repeater holds ImageButtons.
The aspx:
<asp:Panel ID="panSearch" runat="server" ScrollBars="Vertical" BorderColor="#333333" BorderStyle="Inset" Width="500" Height="200">
<asp:Repeater ID="Repeater" runat="server">
<ItemTemplate>
<asp:ImageButton OnClick="imgSearchResult_Click" BackColor="#333333" ID="imgSearchResult" height="32" width="32" runat="server" ImageUrl='<%# Eval("ImageUrl") %>'/>
</ItemTemplate>
</asp:Repeater>
</asp:Panel>
Additionally, I have a TextBox, which has a TextChanged-event in code-behind. I do a few things in there and at the end, my Repeater's DataSource will be overwritten with a new List of images (those images are put into the ImageButtons).
Repeater.DataSource = ImageList;
Repeater.DataBind();
My problem: Whenever my Repeater.DataSource is changed, it "clicks" the first ImageButton inside the Repeater. How do I prevent that from happening?
Full code:
My TextBox:
<asp:TextBox ID="textSearch" runat="server" Width="80" OnTextChanged="textSearch_TextChanged" ForeColor="Black" />
My TextChanged event:
protected void textSearch_TextChanged(object sender, EventArgs e)
{
string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Images/ORAS"));
List<System.Web.UI.WebControls.Image> ImageList = new List<System.Web.UI.WebControls.Image>(filesindirectory.Count());
foreach (string item in filesindirectory)
{
System.Web.UI.WebControls.Image myImage= new System.Web.UI.WebControls.Image();
myImage.ImageUrl = (String.Format("~/Images/ORAS/{0}", System.IO.Path.GetFileName(item)));
ImageList.Add(myImage);
}
Repeater.DataSource = ImageList;
Repeater.DataBind();
}
When I click on an ImageButton inside the Repeater (which is executed when the text in my TextBox is changed):
protected void imgSearchResult_Click(object sender, ImageClickEventArgs e)
{
var selectedImage = sender as ImageButton;
if (img1.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img1.ImageUrl = selectedImage.ImageUrl;
}
else if (img2.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img2.ImageUrl = selectedImage.ImageUrl;
}
else if (img3.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img3.ImageUrl = selectedImage.ImageUrl;
}
else if (img4.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img4.ImageUrl = selectedImage.ImageUrl;
}
else if (img5.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img5.ImageUrl = selectedImage.ImageUrl;
}
else if (img6.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img6.ImageUrl = selectedImage.ImageUrl;
}
else
{
ErrorMessage("Please remove one Image first!", true);
}
}
Pageload:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
img1.ImageUrl = "~/Images/ORAS/Empty/000.png";
img2.ImageUrl = "~/Images/ORAS/Empty/000.png";
img3.ImageUrl = "~/Images/ORAS/Empty/000.png";
img4.ImageUrl = "~/Images/ORAS/Empty/000.png";
img5.ImageUrl = "~/Images/ORAS/Empty/000.png";
img6.ImageUrl = "~/Images/ORAS/Empty/000.png";
LoadImages();
}
}
(LoadImages is almost 1:1 what's in my TextChanged function)
I really am not sure how (why) ASP.NET WebForms does it, but if you hit Enter and the form posts back, it will find the first control that implements IPostBackEventHandler and execute whatever event is bound to that. ImageButton implements it and so that's why it keeps firing the click event even though you didn't click on it. And, once again, only if you hit Enter.
I think that behaviour happens because the data posted back - __EVENTTARGET and __EVENTARGUMENT - are empty. Then ASP.NET goes bonkers.
You can solve it by putting a dummy button at the top of the page (or masterpage) and hide it using the style attribute. so:
<asp:Button ID="dummy" runat="server" style="display:none" />
Then in the init or load of your page (or masterpage) put
Form.DefaultButton = dummy.UniqueID;
That will force the button to capture the enter press instead of the arbitrary image button.

enable an asp.net panel on dropdownlist onselectindexchanged

I want to enable a panel based on dropdownlist selected value.
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddl.SelectedValue == "A")
{
lnk.Style.Add("Display", "block");
panel1.Visible=true;
panel1.Enabled=true;
}
}
The panel is not getting displayed. I have set autopastback property of dropdownlist to true.Can someone please help me.
should be without the quotes:
panel1.Enabled = true;
but if you wanted to show hide a panel:
<asp:Panel ID="panel1" runat="server" Visible="False" >
...
</asp:Panel>
then the right way would be
panel1.Visible = true;//false to hide

DropDown list not firing change event when it is altered

I have a page with a dropdownlist and a button on it. The initial selection on the dropdown is an empty string. I do not want this submitted to the server so I disable the button. I then want to enable the button if any other selection is made on the dropdown. However my ddlBusinessUnit_SelectedIndexChanged method is never hit when I make changes in the dropdown list.
html:
<asp:DropDownList ID="ddlBusinessUnit" EnableViewState="true" runat="server"
OnSelectedIndexChanged="ddlBusinessUnit_SelectedIndexChanged" />
code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dsDate.Date = DateTime.Today;
PopulateBusinessUnits();
StatusMessages.Visible = false;
}
bGetFiles.Enabled = false;
}
public void ddlBusinessUnit_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlBusinessUnit.SelectedItem.Text != "")
bGetFiles.Enabled = true;
}
Set AutoPostBack="true" for your dropdown.
<asp:DropDownList ID="ddlBusinessUnit" EnableViewState="true" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="ddlBusinessUnit_SelectedIndexChanged" />
you're missing AutoPostBack="true" on your asp dropdown control

TextChanged doesn't fire

I am trying to generate textboxes when the I press button add more so this is the code for onclick
protected void Add_TextBoxes(object sender, EventArgs e)
{
int index = int.Parse(ViewState["pickindex"].ToString());
TextBox MyTextBox = new TextBox();
MyTextBox.ID = "tbautogenerated"+index.ToString();
MyTextBox.Text = "tbautogenerated" + index.ToString();
MyTextBox.Width= 250;
MyTextBox.MaxLength = 128;
MyTextBox.Attributes.Add("runat", "server");
MyTextBox.CausesValidation = false;
MyTextBox.AutoPostBack = true;
MyTextBox.TextChanged += new EventHandler(MyTextBox_TextChanged);
picktexts.Controls.Add(MyTextBox);
}
void MyTextBox_TextChanged(object sender, EventArgs e)
{
TextBox MyTextBox = sender as TextBox;
}
but when I change in the textbox the textChanged doesn't work !!! what's wrong ?
HTML Code
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div id="picktexts" runat="server">
<asp:TextBox ID="txtAdress" runat="server" MaxLength="128" Width="250" />
<asp:RequiredFieldValidator ControlToValidate="txtAdress" Display="Dynamic" ID="rfvAddress" Text="* Required" runat="server" />
<asp:Button ID="bt_addtxtbox" runat="server" Text="Add more" OnClick="Add_TextBoxes" CausesValidation="false" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
I think the event handlers are getting lost between posts. the way ASP.NET works, every time you post a page back to itself, all objects are instantiated again, and their state is recovered from the ViewState. Normally a control that's declared in the aspx would reassociate itself with events by the declaration in its tag, which is not the case here.
So try associating the event handlers again during the page load. Like this:
void Page_Load (object sender, EventArgs e)
{
foreach (Control c in picktexts.Controls)
{
((TextBox)c).TextChanged += new EventHandler(MyTextBox_TextChanged);
}
}
And see if it works.

Find Control Inside ListView Control

I want to find "Label" control with ID = "Label" inside the "ListView" control. I was trying to do this with the following code:
((Label)this.ChatListView.FindControl("Label")).Text = "active";
But I am getting this exception: Object reference not set to an instance of an object .
What is wrong here ?
This is aspx code:
<asp:ListView ID="ChatListView" runat="server" DataSourceID="EntityDataSourceUserPosts">
<ItemTemplate>
<div class="post">
<div class="postHeader">
<h2><asp:Label ID="Label1" runat="server"
Text= '<%# Eval("Title") + " by " + this.GetUserFromPost((Guid?)Eval("AuthorUserID")) %>' ></asp:Label></h2>
<asp:Label ID="Label" runat="server" Text="" Visible="True"></asp:Label>
<div class="dateTimePost">
<%# Eval("PostDate")%>
</div>
</div>
<div class="postContent">
<%# Eval("PostComment") %>
</div>
</div>
</ItemTemplate>
</asp:ListView>
Listview is a databound control; so controls inside it will have different ids for different rows. You have to first detect the row, then grab the control. Best to grab such controls is inside an event like OnItemDataBound. There, you can do this to grab your control:
protected void myListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
var yourLabel = e.Item.FindControl("Label1") as Label;
// ...
}
}
If you want to grab it in Page_Load, you will have to know specific row and retrieve the control as:
var theLabel = this.ChatListView.Items[<row_index>].FindControl("Label1") as Label;
This function will get Author Name from a database, you just need to call your method to get Author Name and then return it
protected string GetUserFromPost(Guid? x)
{
// call your function to get Author Name
return "User Name";
}
And to bind label in the list view you have to do it in list view ItemDataBound Event
protected void ChatListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Label lbl = e.Item.FindControl("Label") as Label;
lbl.Text = "Active";
}
}
Here are the list view aspx code changes (just add onitemdatabound="ChatListView_ItemDataBound"):
asp:ListView
ID="ChatListView"
runat="server"
DataSourceID="EntityDataSourceUserPosts"
onitemdatabound="ChatListView_ItemDataBound"
It should be Label1 in the arguement:
((Label)this.ChatListView.FindControl("Label1")).Text = "active";
This should be in a databound event.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemdatabound.aspx
Try it:
protected void ChatListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item is ListViewDataItem)
{
var yourLabel = e.Item.FindControl("Label1") as Label;
// ...
}
}
One simple solution to this problem, which avoids the FindControl code is to place OnInit on your label.
This would change your page code to this: <asp:Label ID="Label" runat="server" Text="" Visible="True" OnInit="Label_Init"></asp:Label>
And in your code behind you will now have a function like this:
protected void Label_Init(object sender, EventArgs e)
{
Label lblMyLabel = (Label)sender;
lblMyLabel.Text = "My Text";
}

Categories