ASP.NET - Fetch data from dynamically created controls

Asked By Anandh Ramanujam on 24-Nov-11 09:48 AM
Hi,

I am creating a checkboxlist control dynamically and populate the data.

On submit, i have to retrieve the selected items from the checkboxlist

How can we do that.

Thanks.
Riley K replied to Anandh Ramanujam on 24-Nov-11 10:02 AM



Iterate through the checked items and if selected process your code


here is example

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
  
  
    Dim CheckedIndexes As String = ""
    Dim CheckedText As String = ""
  
    For i As Integer = 0 To Me.cbxlist.Items.Count - 1
      If Me.cbxlist.Items(i).Selected Then
CheckedIndexes &= "Index=" & Me.cbxlist.Items(i).Value & ControlChars.CrLf
      End If
    Next
  
    ' Breakpoint here to view
    CheckedIndexes = ""
  
  End Sub


Regards
Anoop S replied to Anandh Ramanujam on 24-Nov-11 10:06 AM
Try this

foreach (ListItem item in ((CheckBoxList)Form.FindControl("cblActivities")).Items)
        {
          if (item.Selected)
          {
           string Activities += item.Value;  
            
          }
        }
Response.Write(Activities);
kalpana aparnathi replied to Anandh Ramanujam on 24-Nov-11 12:41 PM
Try this Code:

protected void Page_Load(object sender, System.EventArgs e)
  {
  if (this.IsPostBack == false)
  {
    chklst.Items.Add("C");
    chklst.Items.Add("C++");
    chklst.Items.Add("C#");
    chklst.Items.Add("Visual Basic 6.0");
    chklst.Items.Add("VB.NET");
    chklst.Items.Add("Pascal");
  }
  }
  protected void cmdsubmit_Click(object sender, System.EventArgs e)
  {
  lblResult.Text = "You chose:<b>";

  foreach (ListItem lstItem in chklst.Items)
  {
    if (lstItem.Selected == true)
    {
    // Add text to label.
    lblResult.Text += "<br />" + lstItem.Text;
    }
  }

  lblResult.Text += "</b>";
  }
dipa ahuja replied to Anandh Ramanujam on 24-Nov-11 12:42 PM
Try this:

protected void Button2_Click(object sender, EventArgs e)
{
  //find id of dynamic textbox
  TextBox tx = (TextBox)Page.FindControl("txt1");
 
  CheckBoxList chkList = (CheckBoxList)Page.FindControl("HobbiesList");
 
  Response.Write("Your Hobbies List");
  Response.Write("-------------------");
  foreach (ListItem items in chkList.Items)
  {
    if (items.Selected)
    {
      Response.Write(items.Text);
    }
  }    
}
Jitendra Faye replied to Anandh Ramanujam on 24-Nov-11 11:55 PM
To get controls to persist you must create them before page initialization.

Example:

override protected void OnInit(EventArgs e)
{

//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();

// YOUR METHOD TO GENERATE DYNAMIC CONTROLS
preInit();

base.OnInit(e);
}

protected void preInit()
{
// GENERATE CONTROLS
}

After that you can get values.