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!
Related
In my application I have a radschedular , when creating a new appointment I am opening in advance mode by specifying StartInsertingInAdvancedForm="True"
My code is given below
.aspx
<telerik:RadScheduler RenderMode="Lightweight" runat="server" ID="rs_course_schedule" CustomAttributeNames="Completed"
StartInsertingInAdvancedForm="True" StartEditingInAdvancedForm="True"
FirstDayOfWeek="Monday" LastDayOfWeek="Friday" Reminders-Enabled="true" SelectedView="WeekView"
RowHeight="30px" AppointmentStyleMode="Simple" OnAppointmentDataBound="RadScheduler1_AppointmentDataBound"
OnAppointmentCommand="rs_course_schedule_OnAppointmentCommand"
OnAppointmentCreated="RadScheduler1_AppointmentCreated" OverflowBehavior="Auto" Skin="Web20"
OnAppointmentInsert="rs_course_schedule_OnAppointmentInsert">
<AdvancedForm Modal="true"></AdvancedForm>
<AppointmentTemplate>
<div class="appointmentHeader">
<asp:Panel ID="RecurrencePanel" CssClass="rsAptRecurrence" runat="server" Visible="false">
</asp:Panel>
<asp:Panel ID="RecurrenceExceptionPanel" CssClass="rsAptRecurrenceException" runat="server"
Visible="false">
</asp:Panel>
<asp:Panel ID="ReminderPanel" CssClass="rsAptReminder" runat="server" Visible="false">
</asp:Panel>
<%#Eval("Subject") %>
</div>
<div>
Assigned to: <strong>
<asp:Label ID="UserLabel" runat="server" Text='<%# Container.Appointment.Resources.GetResourceByType("Faculty") == null ? "None" : Container.Appointment.Resources.GetResourceByType("Faculty").Text %>'></asp:Label>
</strong>
<br />
<asp:CheckBox ID="CompletedStatusCheckBox" runat="server" Text="Completed? " TextAlign="Left"
Checked='<%# !String.IsNullOrEmpty(Container.Appointment.Attributes["Completed"]) && Boolean.Parse(Container.Appointment.Attributes["Completed"]) %>'
AutoPostBack="true" OnCheckedChanged="CompletedStatusCheckBox_CheckedChanged"></asp:CheckBox>
</div>
</AppointmentTemplate>
<ResourceStyles>
<telerik:ResourceStyleMapping Type="Faculty" Key="1" BackColor="red"></telerik:ResourceStyleMapping>
<telerik:ResourceStyleMapping Type="Faculty" Key="2" BackColor="Pink"></telerik:ResourceStyleMapping>
<telerik:ResourceStyleMapping Type="Faculty" Key="3" BackColor="OrangeRed"></telerik:ResourceStyleMapping>
</ResourceStyles>
</telerik:RadScheduler>
in code behind
public partial class Schedule : System.Web.UI.UserControl
{
#region Object Instantiation
readonly BEL_LMS _objLms = new BEL_LMS();
readonly BL_LMS _blLms = new BL_LMS();
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateSchedular();
AddTeachers();
SetDate();
}
}
private void AddTeachers()
{
_objLms.ActivityId = Session["activity_id"].ToString();
DataTable dtFaculty = _blLms.AssignedFaculty(_objLms);
ResourceType resources = new ResourceType("Faculty");
if (dtFaculty.Rows.Count > 0)
{
resources.DataSource = dtFaculty;
resources.KeyField = "userid";
resources.TextField = "acct_name";
resources.ForeignKeyField = "UserId";
rs_course_schedule.ResourceTypes.Add(resources);
}
}
private void SetDate()
{
rs_course_schedule.SelectedDate = DateTime.Now;
}
private void PopulateSchedular()
{
_objLms.Flag = "fetch";
_objLms.ActivityId = "11";
DataTable dtTable = _blLms.FetchScheduleForCourse(_objLms);
if (dtTable.Rows.Count > 0)
{
rs_course_schedule.DataKeyField = "ID";
rs_course_schedule.DataStartField = "Start";
rs_course_schedule.DataEndField = "End";
rs_course_schedule.DataSubjectField = "Subject";
rs_course_schedule.DataDescriptionField = "Description";
//rs_course_schedule.DataReminderField = "Reminder";
rs_course_schedule.DataSource = dtTable;
rs_course_schedule.DataBind();
}
}
protected void CompletedStatusCheckBox_CheckedChanged(object sender, EventArgs e)
{
CheckBox CompletedStatusCheckBox = (CheckBox)sender;
//Find the appointment object to directly interact with it
SchedulerAppointmentContainer appContainer = (SchedulerAppointmentContainer)CompletedStatusCheckBox.Parent;
Appointment appointment = appContainer.Appointment;
_objLms.ActivityId = appointment.ID.ToString();
_objLms.Flag = "update";
int affectedRow = _blLms.UpdateCourse(_objLms); // update checkbox data for that particular schedule
rs_course_schedule.Rebind();
}
protected void RadScheduler1_AppointmentDataBound(object sender, SchedulerEventArgs e)
{
if (e.Appointment.Attributes["Completed"] == "True")
{
e.Appointment.BackColor = System.Drawing.Color.Red;
}
}
protected void RadScheduler1_AppointmentCreated(object sender, AppointmentCreatedEventArgs e)
{
}
protected void rs_course_schedule_OnAppointmentInsert(object sender, AppointmentInsertEventArgs e)
{
SchedulerDataSource.InsertParameters["End"].DefaultValue = e.Appointment.End.ToString();
SchedulerDataSource.InsertParameters["Start"].DefaultValue = e.Appointment.Start.ToString();
SchedulerDataSource.InsertParameters["Subject"].DefaultValue = e.Appointment.Start.ToString();
SchedulerDataSource.InsertParameters["Description"].DefaultValue = e.Appointment.Description;
SchedulerDataSource.InsertParameters["CourseID"].DefaultValue = "1";
//SchedulerDataSource.InsertParameters["User"].DefaultVal;
}
protected void rs_course_schedule_OnAppointmentCommand(object sender, AppointmentCommandEventArgs e)
{
string name = e.CommandName;
}
}
}
Now when I am trying to insert a new appointment this form is opening
But in Save and Cancel button click is not occurring..
How I can solve this issue ?
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.
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());
}
}
Can I use double-click on a asp.net listview? I want to call a function on double-click rather than single i.e ItemCommand.
Is it at all possible?
Ta!
ASPX:
<asp:ListView ID="ListView1" runat="server"
onitemdatabound="ListView1_ItemDataBound" onitemcommand="ListView1_ItemCommand">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" CommandName="DoubleClick" runat="server">LinkButton</asp:LinkButton>
</ItemTemplate>
</asp:ListView>
CS:
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
LinkButton LinkButton1 = (LinkButton)e.Item.FindControl("LinkButton1");
string _jsDouble = ClientScript.GetPostBackClientHyperlink(LinkButton1, "");
LinkButton1.Attributes["ondblclick"] = _jsDouble;
LinkButton1.Attributes["onclick"] = "return false;";
}
}
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "DoubleClick")
{
}
}
If calling function is referring to server side call simple thing would be
private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
{
MessageBox.Show("Double Click Event Called");
}
For more info on same check:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.doubleclick.aspx
And if calling function refers to any client side (Javascript/Jquery call) then you can use:
$('#target').dblclick(function() {
alert('Handler for .dblclick() called.');
})
for more info check here
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
}
}