0

I am working on creating buttons that are created dynamically based the results of a SQL Query:

private void createPagingButtons(DateTime firstDayofWeek, DateTime lastDayofWeek)
{
    int i = 1;
    SqlDataReader returnedQuery = getDefaultUser(firstDayofWeek, lastDayofWeek);
    while (returnedQuery.Read())
    {
        string buttonName = returnedQuery["Person"].ToString();
        System.Diagnostics.Debug.WriteLine(buttonName);
        Button btn = new Button();
        btn.ID = i.ToString();
        btn.Click += new EventHandler(btn_Click);
        btn.Text = buttonName;
        pagingPanel.Controls.Add(btn);
        i++;
    }
}

The way I am trying to assign unique button ID's is by assigning them a number that is incremented each time the while loop iterates:

btn.ID = i.ToString();

But it's not working and I am getting an error: Multiple controls with the same ID '1' were found. FindControl requires that controls have unique IDs.

WHy is this happening and how can I fix it?

David Tunnell
  • 7,252
  • 20
  • 66
  • 124

3 Answers3

2

The only way this could occur is if this method were executed more than one time or if these buttons are somehow persisted during the load and then you call it again. However, dynamic controls are for all intents and purposes not persisted and must be recreated on each post back to be useful.

Thus my conclusion, you're calling it more than once.

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
1

As other users said, this error will be thrown if the function is called more than once. Your function will re-start at one each time it is called. Which will duplicate the IDs.

Assuming this is actually the desired behavior, that your function can be called multiple times and will create new buttons each time. Making your int i = 1; a class level variable would resolve this.

alstonp
  • 700
  • 6
  • 25
-2

Replace i++ with ++i.. This should solve your issue..

Sai Avinash
  • 4,683
  • 17
  • 58
  • 96