Why doesn't my Event Handler fire when I click on a radio button? - button

I have a table in the HTML with 8 columns. The header row is manually populated in the HTML as below.
<asp:Table ID="courseTable" runat="server" CssClass="table table-lg" style="color:white">
<asp:TableRow>
<asp:TableCell><b>Choose One</b></asp:TableCell>
<asp:TableCell><b>Course Name and Title</b></asp:TableCell>
<asp:TableCell Width="101"><b>Course Dates</b></asp:TableCell>
<asp:TableCell><b>Building</b></asp:TableCell>
<asp:TableCell><b>Meeting Times</b></asp:TableCell>
<asp:TableCell><b>Days of Week</b></asp:TableCell>
<asp:TableCell><b>Location</b></asp:TableCell>
<asp:TableCell><b>Term</b></asp:TableCell>
</asp:TableRow>
</asp:Table>
and the code behind is used to populate more rows (with a radio button in the first column)
//Add new row to table
courseTable.Rows.Add(new TableRow());
//Add Cells to new rows
for (int x = 0; x < 10; x++)
{
courseTable.Rows[i + 1].Cells.Add(new TableCell());
}
//Create radio button for new row
RadioButton rdo = new RadioButton();
rdo.ID = response.Sections[i].ToString();
rdo.Text = response.Sections[i].ToString();
rdo.CheckedChanged += rdo_CheckedChanged(rdo, new EventArgs());
//Add buttons and info to table (add 1 since the titles count as a row)
courseTable.Rows[i + 1].Cells[0].Controls.Add(rdo);
courseTable.Rows[i + 1].Cells[1].Text = response.NameTitle[i].ToString();
courseTable.Rows[i + 1].Cells[2].Text = response.SecDates[i].ToString();
courseTable.Rows[i + 1].Cells[3].Text = response.BuildingRoom[i].ToString();
courseTable.Rows[i + 1].Cells[4].Text = response.MeetingTime[i].ToString();
courseTable.Rows[i + 1].Cells[5].Text = response.Days[i].ToString();
courseTable.Rows[i + 1].Cells[6].Text = response.Location[i].ToString();
courseTable.Rows[i + 1].Cells[7].Text = response.Term[i].ToString();
}
}
protected EventHandler rdo_CheckedChanged(object sender, EventArgs e)
{
System.Windows.Forms.MessageBox.Show("clicked"); //test message box
cscId.Value = (sender as RadioButton).ID;
return null;
}
but the Event Handler only fires when the radio buttons are added dynamically to each row. The Event Handler never fires when the user clicks on one of the radio buttons. Thanks for any info.
the test message box within the Event Handler was added to verify this

Just for anyone else who may have this problem...
The reason the event was not firing is because the radio button needed AutoPostBack="true" set. But, unfortunately, the post back messes up the screen because the table was created dynamically.
I'll have to use a GridView control I guess. :(

Related

Fetching values from the DropDownlist on PostBack inside Repeater Control in ASP.Net

I have a Repeater Control on one of my asp.net page, i have some labels and one dropdownlist in the repeater control. Default contents are filled in the label and dropdownlist from the Item_Bound event. Now i want to achieve below:
When user selects another item from the dropdownlist, the labels should be updated accordingly.
My Problem here is, as my default content is coming from the item_bound, it always over-rides the content from the dropdownlist, but if i place the !IsPostBack condition inside Item_Bound event, then on selecting dropdownlist nothing happens.
I have used OnSelectedIndexChange event, and just providing the Response.Write inside the event, but as the DropDownlist values overrides itself, i don't get anything on the response.
Can anyone help me with the logic about how shall i tackle this.
Updated Question:
Ok now i am able to fetch the results in the repeater label with the selectedItems from dropdown, but now my problem is i have binded multiple results inside repeater, i.e. each dropdowns per row, but when i select items from another row, it still assumes the value of the first row. Here is my code for reference:
protected void drpQuantity_SelectedIndexChanged(object sender, EventArgs e) //DropDown inside repeater control.
{
foreach (RepeaterItem item in rptLatestProducts.Items)
{
if (item.ItemType == ListItemType.Item)
{
HiddenField hd = item.FindControl("hdProductId") as HiddenField;
DropDownList drp = item.FindControl("drpQuantity") as DropDownList;
Label mrp = item.FindControl("lblMRP") as Label;
Label ourPrice = item.FindControl("lblOurPrice") as Label;
Label discount = item.FindControl("lblDiscount") as Label;
ScriptManager.RegisterStartupScript(updPriceByUnits, this.GetType(), "alert", "alert('" + hd.Value + "')", true); //Always returns product id of the first row.
objPackage.ProductId = Convert.ToInt32(hd.Value);
objPackage.TownId = objPackage.DefaultTown;
int discountPercent = Convert.ToInt32(objPackage.GetProductPackages().Select("unit=" + drp.SelectedValue + " and productid=" + hd.Value)[0]["Discount"].ToString());
mrp.Text = "<span class='rupee' style='font-size:14px;'>Rs</span>" + objPackage.GetProductPackages().Select("unit=" + drp.SelectedValue + " and productid=" + hd.Value)[0]["MRP"].ToString();
ourPrice.Text = "<span class='rupee' style='font-size:14px;'>Rs</span>" + objPackage.GetProductPackages().Select("unit=" + drp.SelectedValue + " and productid=" + hd.Value)[0]["Price"].ToString();
mrp.Visible = (mrp.Text != ourPrice.Text);
if (discountPercent > 0)
{
discount.Visible = true;
discount.Text = objPackage.GetProductPackages().Select("unit=" + drp.SelectedValue + " and productid=" + hd.Value)[0]["Discount"].ToString() + "% OFF";
}
else
{
discount.Visible = false;
}
}
}
}
Can anyone please help me with this
Sounds like you are putting the !Page.IsPostBack around the wrong bit of code.
You need to put this around your DataBind code. So;
if (!Page.IsPostBack){
this.myRepeater.DataSource = [yourdatasource];
this.myRepeater.DataBind();
}
This way your DropDownList controls are not rebound.

Event for Dynamically created Controls in ASP.Net

I've created an application in which I've created Dynamic Controls on Click Event of a Button. But the dynamically created Control Event will not Fire on Click of it.
Below is the Code I've written.
ImageButton closeImage = new ImageButton();
closeImage.ID = "ID"+ dr["ID"].ToString();
closeImage.AlternateText = "Delete";
closeImage.ImageUrl = "App_Themes/images/CloseButton.png";
closeImage.Attributes.Add("style", "float:right;cursor:pointer;margin: -19px 1px -10px;");
closeImage.EnableViewState = true;
closeImage.CommandName = "Delete";
closeImage.CommandArgument = dr["ID"].ToString();
closeImage.Attributes.Add("runat", "server");
closeImage.OnClientClick = "return confirm('Are you sure you want to remove this');";
closeImage.Click += new ImageClickEventHandler(this.closeImage_click);
protected void closeImage_click(object sender, ImageClickEventArgs e)
{
ImageButton ibDel = (ImageButton)sender;
}
The same code work if its placed on Page_Load(). Is there any other Solution to fire the event.
I would like to suggest that you read up on the following article on MSDN. It's about page lifecycle.The key part is to when controls are created. If the controls are created in the wrong stage, events will not be registered, and thus will not fire.
http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.80%29.aspx

How to add tab page in Devexpress TabControl on button click?

I have a Devexpress Tabcontrol.
Inside that Tabcontrol I am having Devexpress Grid.
Inside that Grid I am loading button on run-time by following code.
GridViewCommandColumn col = new GridViewCommandColumn();
GridViewCommandColumnCustomButton CusButton = new GridViewCommandColumnCustomButton();
CusButton.ID = "btn1";
CusButton.Image.Url = "~/Images/color.jpg";
col.ButtonType = ButtonType.Image;
col.CustomButtons.Add(CusButton);
gridview.Columns.Add(col);
Now on that button click, I need to add a Tab page in that Devexpress Tabcontrol retaining this Grid on first tab.
But its not getting added, its getting refreshed on that button click
I just created an object for Tab page and loaded Gridcontrol.ascx user control which has devexpress gridview.
After that I just called addTabPages method in my Tabpage usercontrol and passed this Tabpage object as a parameter in it.In below code tabPreview is the object for Tabcontrol usercontrol.
tabpagenew = new TabPage();
Gc = (GridControl)Page.LoadControl(#"GridControl.ascx");
Gc.ID = "GC" + currDDIndex;
ASPxGridView grdPreview = (ASPxGridView)Gc.FindControl("ggc_preview");
grdPreview.ID = "grd" + currDDIndex;
tabpagenew.Controls.Add(Gc);
tabPreview.addTabPages(tabpagenew);
In addTabPages method, I just added Tab pages by its index,
public void addTabPages(TabPage tab_Page)
{
ActiveIndex = ASPxPageControl1.ActiveTabIndex + 1;
int index = ASPxPageControl1.TabPages.Count + 1;
ASPxPageControl1.TabPages.Add(tab_Page);
tab_Page.ToolTip = tab_Page.Text;
tab_Page.Name = tab_Page.Name;
ImageButton button = new ImageButton();
button.ImageUrl = "~\\Images\\close.png";
button.Style.Add(HtmlTextWriterStyle.Cursor, "Hand");
button.Click += new ImageClickEventHandler(Close_Click);
button.Attributes.Add("onclick", "TabClose('" + hdnCurrentTab.ClientID + "','" + tab_Page.Index + "');");
tab_Page.TabTemplate = new AddTabHeading(button, tab_Page.Text, ASPxPopupMenu1, ASPxPageControl1.ActiveTabPage.VisibleIndex, ASPxPageControl1);
}
In your aspx page:
You need to put the tab control between asp:UpdatePanel.
Add a button inside hidden DIV.
Whenever you need to add a new tab, call the button click function.
This is the code:
<asp:UpdatePanel runat="server" ID="ClientDetailsUpdatePanel" >
<ContentTemplate>
<div style="display:none">
<asp:Button ID="CallBackHiddenButton" runat="server" OnClick="CallBackHiddenButton_Click" Text="Button"/>
</div>
<dx:ASPxPageControl ID="DetailsClientTabs" ClientInstanceName="DetailsClientTabs" runat="server" ActiveTabIndex="0"
ActiveTabStyle-Border-BorderStyle="None" EnableCallBacks="false"
ActiveTabStyle-BackColor="Transparent" ContentStyle-BackColor="Transparent"
ContentStyle-BorderRight-BorderStyle="None" ContentStyle-BorderLeft-BorderStyle="None"
ContentStyle-BorderTop-BorderStyle="None" ContentStyle-BorderBottom-BorderStyle="None"
EnableTheming="False" ContentStyle-Border-BorderColor="Transparent">
</dx:ASPxPageControl>
</ContentTemplate>
</asp:UpdatePanel>
Now in your C# code:
1- Handle the button click to add a new page:
protected void CallBackHiddenButton_Click(object sender, EventArgs e)
{
TabPage newPage = new TabPage("test" + DateTime.Now.Second, "maged" + DateTime.Now.Second);
DetailsClientTabs.TabPages.Add(newPage);
//You always need to reassign the previous tabs pages
for (int i = 0; i < DetailsClientTabs.TabPages.Count; i++)
{
Control cc = Page.LoadControl("~/Forms/Client/Details/TabsPages/TestUserCtrl.ascx");
cc.ID = String.Format("control_di_", DateTime.Now);
DetailsClientTabs.TabPages[i].Controls.Add(cc);
}
//If you need to get the new added tab to be the active one!
DetailsClientTabs.ActiveTabIndex = DetailsClientTabs.TabPages.Count - 1;
}
This may help you.

ASP.NET with VB. ListBox adding and removing items

Hiya i'm creating a web form and i want a user to be able to make certain selections and then add the selections to a text box or listbox.
Basically i want them to be able to type someone name in a text box ... check some check boxes and for it up date either a text for or a list box with the result on button click...
e.g.
John Smith Check1 Check3 Check5
any help would be great .. thanks
I will show you a basic example of a TextBox, Button and a ListBox. When the button is clicked the text will be added to the listbox.
// in your .aspx file
<asp:TextBox ID="yourTextBox" runat="server" /><br />
<asp:Button ID="yourButton" runat="server" Text="Add" OnClick="yourButton_Click" /><br />
<asp:ListBox ID="yourListBox" runat="server" /><br />
// in your codebehind .cs file
protected void yourButton_Click(object sender, EventArgs e)
{
yourListBox.Items.Add(yourTextBox.Text);
}
If you want to use javascript / jquery to do this your could just omit the server side event and just add the following function to the Click property of the button.
$(document).ready(function()
{
$("#yourButton").click(function()
{
$("#yourListBox").append(
new Option($('input[name=yourTextBox]').val(),
'Add value here if you need a value'));
});
});
Lets Suppose you have a gridview which is being populated on Searching happened using Textbox.
Gridivew got some checkboxes and after selection of these checkboxes you wanted to add into listbox
Here is the javascript which will help you to add into listbox.
Please modify as per your requirement,I have less time giving you only a javascript.
function addItmList(idv,valItem) {
var list =document.getElementById('ctl00_ContentPlaceHolder1_MyList');
//var generatedName = "newItem" + ( list.options.length + 1 );
list.Add(idv,valItem);
}
function checkitemvalues()
{
var gvET = document.getElementById("ctl00_ContentPlaceHolder1_grd");
var target = document.getElementById('ctl00_ContentPlaceHolder1_lstIControl');
var newOption = window.document.createElement('OPTION');
var rCount = gvET.rows.length;
var rowIdx = 0;
var tcount = 1;
for (rowIdx; rowIdx<=rCount-1; rowIdx++) {
var rowElement = gvET.rows[rowIdx];
var chkBox = rowElement.cells[0].firstChild;
var cod = rowElement.cells[1].innerText;
var desc = rowElement.cells[2].innerText;
if (chkBox.checked == true){
addItmList(rowElement.cells[1].innerText,rowElement.cells[2].innerText);
}
}
}

Problem getting commandeventargs in command event following re-creationg of controls in postback

I am haveing problems getting the command event args following the second click using the code below.
so - when i process a button click, and generate a new button to replace the one that was there i lose the viewstate on the next button click.
Any suggestions on what I need to do to get this to work? I cannot significantly change the structure as I must generate a variable number of totally un-related buttons in the command handler.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
LinkButton btn = new LinkButton();
btn.ID = "btn1";
this.Panel1.Controls.Add(btn);
btn.Command += new CommandEventHandler(myLinkButton_Command);
}
else
{
LinkButton btn = new LinkButton();
btn.ID = "btn1";
this.Panel1.Controls.Add(btn);
btn.Text = "My Button 1";
btn.CommandArgument = "1";
btn.Command += new CommandEventHandler(myLinkButton_Command);
}
}
void myLinkButton_Command(object sender, CommandEventArgs e)
{
int newArg = Convert.ToInt32(e.CommandArgument) + 1;// empty string on second mouse click
this.Panel1.Controls.Clear();
LinkButton myLinkButton = new LinkButton();
myLinkButton.ID = "btn1";
this.Panel1.Controls.Add(myLinkButton);
myLinkButton.Text = "My Button " + newArg.ToString();
myLinkButton.CommandArgument = newArg.ToString();
}
}
This happens because your panel has a literal control in it. When you add your button the first time, it (the button) is a second control. When you later clear panel's controls collection, it becomes the first control and the viewstate is saved for the first control, which on following postback becomes the literal.
Simply convert
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
to
<asp:Panel ID="Panel1" runat="server" />
and it will work.
You have forgotten to set the CommandArgument property when you recreate the button in Page_Load.

Resources