.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

Handling event from dynamically generated ImageButtons

Posted By:      Posted Date: September 05, 2010    Points: 0   Category :ASP.Net
Dear all,I have a situation here.Please review the following codeImports MySql.Data.MySqlClient Imports VB = Microsoft.VisualBasic Partial Class AddFriend Inherits System.Web.UI.Page Dim WithEvents btnAccept As ImageButton Dim WithEvents btnReject As ImageButton Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init Dim ConnectionString As String ConnectionString = ConfigurationManager.ConnectionStrings("MySqlConnectionString").ToString.Trim Dim MySqlConnection As New MySqlConnection(ConnectionString) Try MySqlConnection.Open() Dim MySqlCommand As New MySqlCommand("", MySqlConnection) MySqlCommand.CommandText = "Select `ccf`.uuid,`ccf`.requestmsg,`cu`.* from `chittochat`.`cc_friends` as `ccf`, `chittochat`.`cc_users` as `cu` where `cu`.uuid=`ccf`.uuid and `ccf`.fuuid='" & Membership.GetUser(Page.User.Identity.Name.Trim).ProviderUserKey.ToString & "' and `ccf`.accepted=0" Dim Reader As MySqlDataReader = MySqlCommand.ExecuteReader If Reader.HasRows Then Do While Reader.Read() Dim img As New Image With {.Height = 40, .Width = 35, .ImageUrl = "content\userphoto\" & Reader("PhotoURL").ToString.Trim & Reader("PhotoEXT"

View Complete Post

More Related Resource Links

Charset Problem with dynamically generated Word Document


in my asp.net web application i am dynamically generating a word documnet out of a sql data. I have set the char set UTF-8 during the doument creation in code but still when i open the generated document and check it char set .. it is always windows-1252 not the one that i have set. My sql data in the document have special characters whihc can only be understandable using the UTF-8 charset otherwise its always ?T written in place of an apostrophy . Pasting my code here..

         HttpContext.Current.Response.ContentType = "application/msword";
         HttpContext.Current.Response.ContentEncoding = System.Text.UnicodeEncoding.UTF8;
         HttpContext.Current.Response.Charset = "utf-8";
         string strFileName = "Details" + ".doc";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
        StringBuilder strHTMLContent = new StringBuilder();
        string strMessage = " ";
        DataView abstractview = (DataView)dsAbstract.Select(DataSourceSelectArguments.Empty);
        foreach (DataRowView row1 in abstractview)
            strMessage += "<table border='1' cellspacing='0' cellpadding='5' width

Generated controls - skipping focus event - C# + JS


Ok, here is my senario.

A random (6-15) amount of textboxes are generated. Each textbox represents only one character. From those textboxes, three of them (at a random position) are enabled and the rest disabled.


When I put a character in any enabled textbox, it must put the focus on the next enabled textbox.


Textbox IDs go from 'char0' to 'char15' OR 'char0' to 'char12' OR ...

All the textboxes are generated so I can't set up specific focus events for each textbox because the designated control is unknown at design time.

Here is my attempt:


<script type="text/javascript">
    function abc(nextfocus)


for (int i = 0; i < focusableControls.Length-1; i++)
focusableControls[i].ClientSideEvents.KeyDown = "abc(" + focusableControls[i + 1].ID + ")";


focusableControls is an array with all the textboxes in that can get focus. It is also in the right order.

Things I want to find out:

How will I send the textbox out of focus

WPF ComboBox Loaded Event - Handling Globally

Hello, I am having trouble hooking up to a WPF ComboBox Loaded event when trying to do it globally with EventManager.RegisterClassHandler in the parent control rather than with XAML right on the control.  Here is the code for the ComboBox control: <DataTemplate x:Key="MyUIEditor"> <ComboBox Width='Auto' x:Name="Combo" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MyControlWPG}}, Path=MyCollection}" SelectedValue="{Binding Value}" DisplayMemberPath="Name" SelectedValuePath="FullName" Background="Transparent" /> </DataTemplate>   Here is the code for the global event handler:   public partial class MyControlWPG : UserControl public MyControlWPG() { InitializeComponent(); EventManager.RegisterClassHandler(typeof(ComboBox), ComboBox.LoadedEvent, new RoutedEventHandler(Combo_Loaded)); } The event handler gets hit when I declare Loaded = "Combo_Loaded" in the XAML right on the ComboBox control but not when I use the global handler.  Any ideas as to why it doesn't get hit when doing it this way?

Cannot retrieve values of dynamically generated controls

Hi All, I am creating a user control which contains checkboxes and labels that needs to be created on fly. The dynamic generation of these controls depend on the values retreived from a SPlist. I have several panels that display items queried from the list on the basis of a selection criteria. On a button click event I need to capture all the selected values from the controls that were generated dynamically.  When I traverse each dynamic control that I added to the panel, I dont see their values. I tried using recursive retrieval of the control from the page as well but it just behaves crazy, it treats a radio button as a checkbox and returns a value that I am not looking for. I am not using the the page_load() or any other event, I use the button handler on my custom method. I was thinking for ViewState, ControlsState or SessionState. I assume ViewState may not work on this as the dynamically generated controls need to be in the page_load event. Please guide as this getting way more complicated than what I had ever thought of it to be.

client side event handling in asp.net

i should handle a event whn my focus chages from one text box to other......   [  i should get an error as you are not entered the data(it should accept only numbers)  ]

dynamically created button control click event not firing first time?

HI im creating a button control in page int and im assing a click event for the button control. here the click event is not firing for the first time.can anyone help me with this? here is my code. Button btn = new Button(); btn.ID = "btn"; btn.Click += new EventHandler(btn_Click); Panel1.Controls.Add(btn); Panel1.Controls.Add(new LiteralControl(""));

Handling the DoubleClic Event on a GridviewRow.

Hello, I´m trying to handle the DoubleClic event on a GridviewRow.the objective is to show the detail of a row in a form,so  when the user  doubleclic  that row , so the user be able to edit the detail.Right now  i´m adding atributes to the rows in the RowDataBound event, so when the user clic over the row  i capture  the "Index" in the RowCommand event  and in the SelectedIndexChanging i show a "ReadOnly" popup with the data of the row. And it Works!!But now i need ondoubleclic the row and call a C# function, so in that function i´ll load the row data on a "Edit" Form.protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e){           if (e.Row.RowType == DataControlRowType.DataRow){                 e.Row.Attributes["onclick"]=ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);                             //Here is the trouble, HOW CAN I CALL A C# FUNCTION?              //e.Row.Attributes.Add("OnDblClick", "Myc#funtion();");                      }}Waiting your c

Dynamically Generated Dynamic Menu Items Width Question


I have the following Menu:

<asp:Menu ID="MainMenu" runat="server" Orientation="Horizontal" 
	DynamicVerticalOffset="2" DynamicHorizontalOffset="2" 
	StaticEnableDefaultPopOutImage="false" DynamicEnableDefaultPopOutImage="false" >
        <StaticMenuItemStyle BackColor="#0099cc" ForeColor="#eeeeee" Font-Names="Arial" Font-Size="11" Height="18" HorizontalPadding="10" VerticalPadding="3"  />
	<StaticHoverStyle BackColor="#336699" ForeColor="#ffffff" Font-Names="Arial" Font-Size="11" />
	<DynamicMenuItemStyle BackColor="#0099cc" ForeColor="#eeeeee" Font-Names="Arial" Font-Size="10" Height="18" 
		HorizontalPadding="10" VerticalPadding="3" />
	<DynamicHoverStyle BackColor="#336699" ForeColor="#ffffff" Font-Names="Arial" Font-Size="10" />					
		<asp:MenuItemBinding DataMember="Item" TextField="Title" />
		<asp:MenuItemBinding DataMember="SubItem" TextField="Title" />						

TextBox AutoPostBack not working when handling other DHTML event


I have to format a number in a TextBox while it is being typed. Right after the TextBox looses focus, I need to do other processing on server side, including some database queries.

I'm doing the formatting by handling the onkeyup event, client side. But when I add the handler, the onTextChanged event stops firing on the server. I've tried different return values for the handler but unfortunatelly I'm stuck.

To reproduce the problem, here is a sample where the formatting function was replaced by a simple "convert to uppercase" function. You'll see that, contrary to the expected, the Label doesn't get filled when the TextBox looses focus. It does get filled, however, if the user presses the ENTER key.

What can I possibly be doing wrong with such a simple task?


<%@ Page Language="VB" %>

<script language="VB" runat="server">

Sub Page_Load(ByVal Sender As Object, ByVal E As EventArgs)

'' Adding the event handler like this has the same effect as adding it inline

'txtTextBox.Attributes.Add("onkeyup", "return(upperCase(this));")

End Sub

Protected Sub txtTextBox_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)

lblTextBox.Text = S

Loading ImageButtons Dynamically using FindControl


I have a table where each cell contains an ImageButton, with an iterative ID:

	<asp:TableCell ID="zm_1">
		<asp:ImageButton ID="zmi_1"  runat="server" Height="15px" Width="15px" />
	<asp:TableCell ID="zm_2">
		<asp:ImageButton ID="zmi_2"  runat="server" Height="15px" Width="15px" />
	<asp:TableCell ID="zm_3">
		<asp:ImageButton ID="zmi_3"  runat="server" Height="15px" Width="15px" />

I am then trying to assign a URL to each imagebutton dynamically in a separate code file

ContentPlaceHolder MainContent = Page.Master.FindControl("MainContent") as ContentPlaceHolder;
ImageButton button = new ImageButton();
for (int i=1;i <=3; i++)
        button = MainContent.FindControl("zmi_" + i.ToString()) as ImageButton;
        button.ImageUrl = Server.MapPath("~/img/some_image.jpg");

Everything compiles, but when I run this I throw a Null Reference Exception:  {"Object reference not set to an instance of an object."}


Exception thrown when handling Window.Loaded event


Why is the exception assistant not "fired" in a debugging session when a Window.Loaded eventhandler calls code which throws an exception ?
        private void Window_Loaded(object sender, RoutedEventArgs e)
            //Application.Current.DispatcherUnhandledException +=
               new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(Current_DispatcherUnhandledException);
            int a = 1;
            int b = 0;
            int c = a / b;

        void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)

Removing the comment signs (//) thus presenting an UnhandledException handler devinately makes the assistant "firing".
Is this behaviour by desi

Programmatically generated AsyncFileUpload does not fire UploadedComplete event


The AsyncFileUpload control turns green, indicating that the attachment was successfully uploaded, but the designated method for handling the server side UploadedComplete event is never executed.

Bind Event Receiver to List Dynamically


Hey all, I've been working on a little application page that will give users the option to say whether a list should allow duplicate title entries.

I am able to pass the current list GUID to the application page using this:

<UrlAction Url="~site/_layouts/preventduplicates.aspx?List={ListId}"/>

within a custom action which I've added to the list settings. I'm kind of stuck now....


I'm not sure how to grab this GUID out of the url, and use it so I can bind the current list with my event receiver. Every example I've seen of binding has used a hard coded list name which is fine as an example, but isn't the best for real applications. Or is there a way to use the GUID to get the lists name which I can then pass to the spweb.Lists[var] ? Since I won't know the list name beforehand.

Hope all of that makes sense, any suggestions are appreciated.

using __doPostBack with dynamically generated controls


I'm making a page for dynamically handling surveys.  The questions and their related controls (multiple choice, text) are stored in a DB and fed into a page on loading.  For some questions, particular answers will need to disable other questions' controls as they are no longer valid in context.  For example, If the survey asks the user if they've worked in the past year and they respond "No" then I need to disable the choices for the "how much did you earn" question.  The tricky part is that I need to be able to undo this action as well.  If the user now selects "Yes" to the first question, I have to re-enable all the earnings choices.

There are too many controls to always trigger an event whenever something is clicked, so I'd like to limit my postbacks to only those option which can cause a skip to occur.  This becomes a problem for Radio Buttons and DropDown Lists, as I only want the selection/deselection of particular options to cause postback and the others to do nothing (though selection of such an "inert" option will cause postback if it causes the deselection of a skip-causing control).  Not having an equivalent "CheckedChanged" event for Radio Buttons as there is for Checkboxes is irritating.

My solution thus far (for Radio Buttons) is to add t

Problem with gridview dynamically generated columns and textboxes


Hi All,

 I am using asp.net/c# application. In my application, I have a gridview.

<asp:GridView id ="gv_QuestionList" runat="server"> </asp:GridView>

In Code Behind, I created dynamic textboxes and DropDownLists on RowDataBound.

protected void gv_QuestionList_RowDataBound(object sender, GridViewRowEventArgs e)
            if (e.Row.RowType == DataControlRowType.DataRow)

                if (ObjQMDO.QuestionType == "TextBox")
                    TextBox txt = new TextBox();
                else if (ObjQMDO.QuestionType == "Dropdownlist")
                    DropDownList drp = new DropDownList();
                    drp.DataSource = ObjQMDA.GetQuesTypeValues(QUES_ID);
                    drp.DataTextField = "QTYV_QuesTypeValue";
                    drp.DataValueField = "QTYV_ID";
                    drp.Items.Insert(0, new ListItem("Select One", "0"));

                else if (ObjQMDO.QuestionType == "Radio")

add event handler to dynamically created button


Does anyone have a good vb example of adding an "onClick" event to a button that is dynamically added into a templatefield of a gridview.  MSDN just says to use the addhandler statement with no other good info for a 'dynamic' scenario:


Thanks in advance for any advice.


Dynamically Loaded UserControl, receiving the click event from UserControl to Parent Page



   In a page , when I click a button 'showDialog' I am loading the user control dynamically in a dialog.  I am linking to the event in the user control as explained below. The parent page is not receiving this event.

  ex: (This is in the page class)


         UseControl1 gc = dlg.LoadContent(:\UserControl1.csx);

        gc.CausePostback += new EventHandler(execute_CausePostback());



   // I am trying to update the details grid in parent page


In UserControl class after clicking the submit button


  raise event CausePostBack();


Any help is appreciated.



ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend