populate dropdown using a textbox asp.net - asp.net

How to populate a drop down when user enters some text in text box, i have tried using text changed event in the text box control it works, but needs to click twice the drop down, when i clicked first it loads the data and drop drown gets closed, then i again click it shows
i used asp text box and asp drop down
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="true">
</asp:TextBox>
Private Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
DropDownList1.Items.Clear()
DropDownList1.Items.Add(TextBox1.Text)
Dim icount As Integer
icount = DropDownList1.Items.Count
DropDownList1.Items.Add("Select")
DropDownList1.SelectedIndex = icount
End Sub

Try this:
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
and then :
protected void Page_Load(object sender, EventArgs e)
{
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
int count = Convert.ToInt32(this.TextBox1.Text);
for (int i = 1; i <= count; i++)
{
this.DropDownList1.Items.Add(i.ToString());
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write("Selected Value Is :" + this.DropDownList1.SelectedValue);
}
Please let me know if you have some difficulty.

Example : txtCity.text = "Mysore,Bangalore,Delhi"
protected void txtCity_TextChanged(object sender, EventArgs e)
{
string[] _cities=this.txtCity.text.split(',');
int _maxCities = _cities.count();
for (int _item = 1; _item <= _maxCities; _item++)
{
this.ddlCity.Items.Add(_item.ToString());
}
}

Related

asp.net repeater in update panel databind outside page_load

I have repeater in updatePanel asp.net. It works fine when I run databind() in Page_load method. But when databind() is called by some event outside Page_load, repeater cleared. Databind() does not work in this case! What can be reason for this?
this is code ...
this works:
protected void Page_Load(object sender, EventArgs e)
{
........
populateCalendar(Int32.Parse(DDL_YearsList.SelectedValue), Int32.Parse(DDL_MonthsList.SelectedValue), Int32.Parse(DDL_EmployeesList.SelectedValue));
}
private void populateCalendar(int year, int month, int idEmploee)
{
.......
monthShower.DataSource = listWeeks;
monthShower.DataBind();
}
protected void DDL_EmployeesList_SelectedIndexChanged(object sender, EventArgs e)
{
//populateCalendar(Int32.Parse(DDL_YearsList.SelectedValue), Int32.Parse(DDL_MonthsList.SelectedValue), Int32.Parse(DDL_EmployeesList.SelectedValue));
}
this does not work, when DDL_EmployeesList_SelectedIndexChanged fired:
protected void Page_Load(object sender, EventArgs e)
{
........
// populateCalendar(Int32.Parse(DDL_YearsList.SelectedValue), Int32.Parse(DDL_MonthsList.SelectedValue), Int32.Parse(DDL_EmployeesList.SelectedValue));
}
private void populateCalendar(int year, int month, int idEmploee)
{
.......
monthShower.DataSource = listWeeks;
monthShower.DataBind();
}
protected void DDL_EmployeesList_SelectedIndexChanged(object sender, EventArgs e)
{
populateCalendar(Int32.Parse(DDL_YearsList.SelectedValue), Int32.Parse(DDL_MonthsList.SelectedValue), Int32.Parse(DDL_EmployeesList.SelectedValue));
}
<asp:Repeater id ="monthShower" runat ="server"> <ItemTemplate> <custom:DayID="Day1" runat ="server" TblDay =<%# DataBinder.Eval(Container.DataItem, "Monday") %>></custom:Day> </ItemTemplate> </asp:Repeater>
So i did a small test and posted the code
Html:
<div id="test">
<asp:DropDownList runat="server" ID="DropDownList1" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"></asp:DropDownList>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<table>
<asp:Repeater runat="server" ID="repTeste" OnItemDataBound="repTeste_ItemDataBound">
<ItemTemplate>
<tr>
<td runat="server" id="tdTeste">
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
C# - I used pop() in my pageLoad just to populate the ddl:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
populateCalendar(DropDownList1.SelectedValue, 2, 3);
}
private void populateCalendar(String year, int month, int idEmploee)
{
List<String> lis = new List<String>();
lis.Add(year);
repTeste.DataSource = lis;
repTeste.DataBind();
}
private void pop()
{
ListItem li = new ListItem("1", "1");
li.Attributes.Add("title", "1");
DropDownList1.Items.Add(li);
li = new ListItem("2", "2");
li.Attributes.Add("t2itle", "2");
DropDownList1.Items.Add(li);
li = new ListItem("3", "3");
li.Attributes.Add("ti3tle", "3");
DropDownList1.Items.Add(li);
}
protected void repTeste_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
String inte = (String)e.Item.DataItem;
HtmlTableCell td = (HtmlTableCell)e.Item.FindControl("tdTeste");
td.InnerText = inte;
}
it updates correctly.
Since you didn't post your html and the fact that someone deleted my post, i posted my code here for you, you can use it to compare it or you can post your Html and ill give it a look.

asp.net button in ITemplate doesn't fire Repeater ItemCommand event

i am a complete asp.net noob and the solution could be something very simple.
i have found, read and tried many answers to questions very similar to my question, but nothing works. i hope to find some help here.
this works perfectly with no problem:
<asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text='<%# (Container.DataItem as Choice).description %>' CommandName="Choice" CommandArgument='<%# (Container.DataItem as Choice).id %>'/>
<br />
</ItemTemplate>
</asp:Repeater>
code behind:
void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<Choice> choiceList = new List<Choice>();
// ... code to fill the list ...
Repeater1.DataSource = choiceList;
Repeater1.DataBind();
}
}
void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
int idx = int.Parse( e.CommandArgument.ToString() );
// this function is called
}
but if i use ITemplate it doesn't work:
<asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand">
</asp:Repeater>
code behind:
public class MyButtonTemplate : System.Web.UI.ITemplate
{
public void InstantiateIn(System.Web.UI.Control container)
{
Button button = new Button();
button.CommandName = "choice";
button.DataBinding += new EventHandler(Button_DataBinding);
container.Controls.Add(button);
container.Controls.Add(new LiteralControl("<br />"));
}
}
static void Button_DataBinding(object sender, System.EventArgs e)
{
Button button = (Button)sender;
RepeaterItem repeaterItem = (RepeaterItem)button.NamingContainer;
button.ID = "button" + (repeaterItem.DataItem as Choice).id.ToString();
button.CommandArgument = (repeaterItem.DataItem as Choice).id.ToString();
button.Text = (repeaterItem.DataItem as Choice).description;
}
void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<Choice> choiceList = new List<Choice>();
// ... code to fill the list ...
Repeater1.ItemTemplate = new MyButtonTemplate();
Repeater1.DataSource = choiceList;
Repeater1.DataBind();
}
}
void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
int idx = int.Parse( e.CommandArgument.ToString() );
// this function is NOT called
}
the buttons are displayed, but the event is not fired.
i have already tried saving a delegate in MyButtonTemplate and assigning the button click event - it does not work.
thank you!

CheckBox on a GridView

I have a grid view that has 3 columns(Name, Address, Status) and a checkbox.The Status has 3 properties, Active, Pending, and Disabled. The page load all the information from the database. When loading the page, only accounts that are ACTIVE should be displayed (and the checkbox should remain unchecked)
When clicking the checkbox, the page should load the DISABLED, along with the accounts already displayed When the page loads for the first time.
Aspx:
<asp:CheckBox ID="ChkBox1" runat="server" AutoPostBack="true" OnCheckedChanged="cbShowAllColumn_Changed" TextAlign="Right" Text="Show All"/>
</asp:Panel>
Code behind:
protected void cbShowColumn_Changed(object sender, EventArgs e)
{
string columnName = (sender as CheckBox).ID.Substring(1);
gvTest.Columns[(int)Enum.Parse(typeof(AccountColumns), columnName)].Visible = (sender as CheckBox).Checked;
}
protected void cbShowAllColumn_Changed(object sender, EventArgs e)
{
bool _checked = (sender as CheckBox).Checked;
foreach (Control ctrl in pAccount.Controls)
if (ctrl is CheckBox)
{
(ctrl as CheckBox).Checked = _checked;
gvMain.Columns[(int)Enum.Parse(typeof(AccountColumns), (ctrl as CheckBox).ID.Substring(2))].Visible = _checked;
}
}
I compiled a small asp .net page to do what you asked.
Note: In your project, you should probably take the "source" out of the BindGrid method, so that you don't "get" the data from scratch every time the page is posted back to. I did it that way because I used an anonymous type.
Note #2 I converted an int to your enum and then to a string. Since you use real data you should handle that differently, by using the enum itself.
Markup:
<asp:CheckBox ID="ChkBox1" runat="server" AutoPostBack="true" OnCheckedChanged="cbShowAllColumn_Changed" TextAlign="Right" Text="Show All"/>
<br/>
<asp:gridview ID="gvMain" runat="server" >
</asp:gridview>
Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
BindGrid(false);
}
private void BindGrid(bool showActiveOnly)
{
var source = Enumerable.Range(1, 10)
.Select(number => new { number, status = (Enum.ToObject(typeof(Statuses), number % 3)).ToString() });
var filteredSource = source.Where(x => x.status == "Active" || !showActiveOnly);
gvMain.DataSource = filteredSource;
gvMain.DataBind();
}
protected void cbShowAllColumn_Changed(object sender, EventArgs e)
{
bool _checked = (sender as CheckBox).Checked;
BindGrid(_checked);
}
private enum Statuses
{
Active,
Pending,
Disabled
}

C# - Event handler for dynamic buttons

I have a textbox and submit button created using the design mode.
When the submit button is pressed, it will retrieve the user input from the textbox and then make a query to my database.
It will then display a list of dynamic buttons according to the information retrieved from my database.
However, the event handler for the buttons does not fire when clicked. I guess my problem is the postback but I cannot create those buttons in page_load etc. because I need to get the user input (from the textbox when submit button is pressed) before i can load the buttons.
How can i solve this problem?
Thank you.
Edit (codes):
protected void subBtn_Click(object sender, EventArgs e)
{
//database setup codes
.......
while (reader.Read())
{
Button detailsBtn = new Button();
detailsBtn.Text = reader["fName"].ToString();
//doesn't fire
detailsBtn.Click += new EventHandler(detailsBtn_Click);
memPanel.Controls.Add(detailsBtn);
}
}
Main problem is Postback regenerate dynamic controls on each postback if those controls does not exists.
For quick demo see this code
ASPX CODE
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:Panel ID="pnl" runat="server"></asp:Panel>
</form>
ASPX.CS CODE
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
generate();
}
}
public void generate()
{
if (!pnl.HasControls())
{
for (int i = 0; i < 4; i++)
{
Button detailsBtn = new Button();
detailsBtn.Text = "fName" + i.ToString();
detailsBtn.ID = i.ToString();
detailsBtn.Click += new EventHandler(detailsBtn_Click);
pnl.Controls.Add(detailsBtn);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
generate();
}
protected void detailsBtn_Click(object sender, EventArgs e)
{
}
Sound to me like you could easily refactor your page to use a simple <asp:Repeater runat="server" ..></asp:Repeater> instead of dynamically adding controls to a Panel.
Here is a very simple complete sample:
RepeaterTest.aspx
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
<asp:TextBox ID="theTextBox" runat="server"></asp:TextBox>
<asp:Button ID="theButton" runat="server" OnClick="theButton_Click" Text="Click me" />
<asp:Repeater ID="test" runat="server">
<ItemTemplate>
<asp:Button ID="theRepeaterButton" runat="server" Text='<%# Eval("fName") %>' OnClick="theRepeaterButton_Click" />
</ItemTemplate>
</asp:Repeater>
</asp:Content>
RepeaterTest.aspx.cs
public partial class RepeaterTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void theButton_Click(object sender, EventArgs e)
{
string filter = theTextBox.Text;
// below row simulates fetching data using the filter text in the text box
var data = Enumerable.Range(0, 20).Select(i => new { fName = filter + " " + i });
test.DataSource = data;
test.DataBind();
}
protected void theRepeaterButton_Click(object sender, EventArgs e)
{
var button = (Button)sender;
// do something here based on text/commandname/commandargument etc of the button
}
}

Why is the footer-item not included in Repeater.Items?

I need to get a value from a textbox inside a FooterTemplate in the OnClick event of a button. My first thought was to loop through the items-property on my repeater, but as you can see in this sample, it only includes the actual databound items, not the footer-item.
ASPX:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
Item<br />
</ItemTemplate>
<FooterTemplate>
Footer<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:Repeater>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
Code-behind.cs:
protected void Page_Load(object sender, EventArgs e)
{
ListItemCollection items = new ListItemCollection();
items.Add("value1");
items.Add("value2");
Repeater1.DataSource = items;
Repeater1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine(Repeater1.Items.Count);
}
This code will only output "2" as the count, so how do I get to reference my textbox inside the footertemplate?
From the MSDN documentation, the Items is simply a set of RepeaterItems based off the DataSource that you are binding to and does not include items in the Header or FooterTemplates.
If you want to reference the textbox, you can get a reference on ItemDataBound event from the repeater where you can test for the footer.
E.g.
private void Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Footer)
{
TextBox textBox = e.Item.FindControl("TextBox1") as TextBox;
}
}
You can find controls in the repeater. That will give you all the controls in the repeater (RepeaterItems collection). Now you can do something like this:
RepeaterItem footerItem=null;
foreach(Control cnt in Repeater1.Controls)
{
if(cnt.GetType() == typeof(RepeaterItem) && ((RepeaterItem)cnt).ItemType == ListItemType.Footer)
{
footerItem = cnt;
break;
}
}
The footer should be the last child control of the repeater so you can do something like..
RepeaterItem riFooter = Repeater1.Controls[Repeater1.Controls.Count - 1] as RepeaterItem;
if (riFooter != null && riFooter.ItemType == ListItemType.Footer) {
TextBox TextBox1 = riFooter.FindControl("TextBox1") as TextBox;
if (TextBox1 != null) {
TextBox1.Text = "Test";
}
}

Resources