I have an array consisting of LinkButton. It is necessary for each element of the array to create its own handler.

protected void Page_Load(object sender, EventArgs e) { LinkButton[] button = new LinkButton[10]; int i = 0; Query query = new Query(); SqlDataReader myReader = query.ExecuteQuery("select * from myusers"); while (myReader.Read()) { if (i < 10) { LinkButton newbutton = new LinkButton(); newbutton.ID = "but" + i; button[i] = newbutton; query.ExecuteQuery("select ic, name, surname from myusers"); button[i].Text = Convert.ToString(myReader["name"]) +" "+ Convert.ToString(myReader["surname"]); button[i].OnClientClick += new EventHandler(this.link_Click); form1.Controls.Add(button[i]); i++; } } } protected void link_Click(object sender, EventArgs e) { LinkButton link = (LinkButton)sender; Session["name"] = link.Text; } 

But event handling does not occur. Help! What's my mistake?

  • Why button [i] = newbutton? Work with newbutton, it’s all the same for you every time a new one, and then add it to the array. In general, everything is better through the template and Repeater as I have below. - invincible
  • In my opinion this way: LinkButton newbutton = new LinkButton (); newbutton.ID = "but" + i; query.ExecuteQuery ("select ic, name, surname from myusers"); newbutton.Text = Convert.ToString (myReader ["name"]) + "" + Convert.ToString (myReader ["surname"]); newbutton.OnClientClick + = new EventHandler (this.link_Click); button [i] = newbutton; form1.Controls.Add (button [i]); i ++; - invincible
  • one
    Mlyn did not immediately replace, everything is not working for you. The event is client, and the server handler. Try this: newbutton.Click + = new EventHandler (this.link_Click); - invincible
  • thank you so much! everything works now! - lider112

3 answers 3

I publish a more detailed code, since it is not entirely clear:

The form:

 <asp:GridView runat="server" id="RolesGrid" allowpaging="true" autogeneratecolumns="False" border="0" cellpadding="5" cellspacing="0" pagesize="7" width="100%" UseAccessibleHeader="true"> <Columns> <asp:templateField runat="server" headerText="Имя роли" > <itemTemplate> <%# Container.DataItem %> </itemTemplate> </asp:templateField> <asp:templateField runat="server" > <itemStyle horizontalAlign="center"/> <itemTemplate> <asp:linkButton runat="server" id="linkButton2" text="Удалить" commandArgument='<%#Container.DataItem%>' OnCommand='DelRoleClick' OnClientClick="if (confirm('Вы уверены, что хотите удалить эту запись?') == false) return false;" /> </itemTemplate> </asp:templateField> </Columns> </asp:GridView> 

Server:

 //Удаляем роль public void DelRoleClick(object sender, CommandEventArgs e) { string rolename = (string)e.CommandArgument; if(Roles.RoleExists(rolename)) Roles.DeleteRole(rolename); BindRoles(); } //Обновляем список ролей. При первой загрузке эта функция также вызывается, чтобы инициализировать список public void BindRoles() { string[] arr = Roles.GetAllRoles(); RolesGrid.DataSource = arr; RolesGrid.DataBind(); } 

Here's another option with Repeater:

 <asp:Repeater ID="rptAlphabet" runat="server" OnItemCommand="rptAlphabet_ItemCommand"> <ItemTemplate> <asp:LinkButton CommandArgument='<%# Container.DataItem %>' runat="server"><%# Container.DataItem %></asp:LinkButton> </ItemTemplate> </asp:Repeater> 

We fill the list when loading:

 string[] alphabet = "a;b;c;d;e;f;g;h;i;j;k;l;m;n;o;p;q;r;s;t;u;v;w;x;y;z;все".Split(';'); rptAlphabet.DataSource = alphabet; rptAlphabet.DataBind(); 

We process pressing:

 protected void rptAlphabet_ItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandArgument.ToString().Length == 1){ gvwUsers.Attributes.Add("SearchText", e.CommandArgument.ToString() + "%"); BindUsers(false); } } 
  • so I have an array from LinkButton, they are created dynamically depending on how much data I have, so the handler needs to be written programmatically ... - lider112
  • I also dynamically, and who prevents the template to use? Completed the answer to make it clearer. If you have more questions, I will be happy to help. - invincible
  • Well, or give your code, in place correct it. - invincible
  • Added option with repiaterom, see above. - invincible
  • look at my code above! - lider112

Most likely, this is due to the fact that the button handler in the other instance of the form is processed in relation to the one in which it was created.

  • The user has opened a web form.
  • The handler of Page_Load was caused, buttons were created.
  • The form, together with the buttons, was rendered and destroyed.
  • User pressed a button
  • PostBasck occurs
  • A new web form instance is created on the server.
  • Buttons were created again in Page_Load, but these are new buttons, not those whose events need to be processed.

It's not entirely clear why you are subscribing to OnClientClick, and not to OnClick.

  • what do i need to fix in that case ?? - lider112
  • I would put a link to the Repeater and the handler for it would be specified in the aspx file through the attribute. - Modus
  • You can write sample code, if not hard !! - lider112

Because OnClick is not available. OnClientClick for processing on the client, and he does not cause an event on the server. This is obviously the wrong way!

  • Try to write more detailed answers. Explain what is the basis of your statement? - Nicolas Chabanovsky