简体   繁体   中英

Dynamically add textbox next to checkbox list option in asp.net webform

I need to populate checkbox list from database and next to each checkbox i need to add textbox so that user can numeric value in the text box.

I also need to save checked checkbox value in a different table

Table Project {Projectid, Name, Details, cDate}

Table ContributionForProject{id, Name, Amount, Projectid, cDate,GUID}

Table TotalContribusion{id, TotalAmount, Projectid, cDate, GUID}

I am using below code to fill the checkedlist box and showing textbox next to each option.

in order to save value in the database i need to get the corresponding values from textbox also.

I have two issues with this.

  1. How can i identify projectID for each checbox as i can't pass value option for checkbox
  2. How can i get the values for each checked checklistbox & related textbox so that i can loop through & save.

Below is the code which i am working with

public void CreateChecklistWithOption()
    {
        var MyList = new List<ListItem>
        {
            new ListItem("Project One", "1"),
            new ListItem("Project Two", "2"),
            new ListItem("Project Three", "3"),
            new ListItem("Project Four", "4")
        };

        Table myTable = new Table();

        foreach (var item in MyList)
        {
            //Create new checkbox
            CheckBox CB = new CheckBox();
            CB.Text = item.Text;
            CB.ID = "CB_"+item.Value;


            //Create tablr row and td, then adds them accordignly
            TableRow TR = new TableRow();
            TableCell TD = new TableCell();
            TD.Controls.Add(CB);
            TR.Controls.Add(TD);

            //IF <YOUR FLAG GOES HERE>-->
            //if (item.Value == "2" || item.Value == "1" || item.Value == "3")
            //{
                //Create your input element and place it in a new Table cell (TD2)
                TextBox TB = new TextBox();
                TB.ID = string.Format("tb_{0}", item.Value);
                TableCell TD2 = new TableCell();
                TD2.Controls.Add(TB);
                TR.Controls.Add(TD2);
            //}

            myTable.Controls.Add(TR);
        }

        phforCheckList.Controls.Add(myTable);
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Response.Write("<br> Ckeck Box One  " );
        Response.Write("<br> Ckeck Box Two  ");
        Response.Write("<br> Ckeck Box Three  ");
    }


  <asp:PlaceHolder ID="fillMe" runat="server"></asp:PlaceHolder>

  1. Use the Checked attribute, not value .
  2. Dynamic controls usually are added in the Page_Init event of a WebForms page, then you can access them anywhere you need. Read about FindControl .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM