Question

i'm working on a project which will keep records of a repair service and list them in a page. I have a gridview to list records. That gridview will contain a dropdownlist which will show options about the state of the current record. I can create this dropdownlist in asp side with this :

<asp:TemplateField>
       <ItemTemplate>
             <asp:DropDownList runat="server" ID="test_drop1">
             </asp:DropDownList>
        </ItemTemplate>
</asp:TemplateField>

but in my situation if i could create that gridview in c# side, it would be better. The problem is i couldn't assign the dropdownlist to templatefield in c# . Any idea how to do that? Thanks in advance.

Was it helpful?

Solution

    private void BindGrid()
      {
        DataTable dt = new DataTable();
        dt.Columns.Add("Test DropDown");

        Control container = new Control();
        TemplateField tf = new TemplateField();
        string chkRole = "ddlTest";


        tf.ItemTemplate = new CreateDropDownList(chkRole);
        //tf.HeaderText = dt.Columns[i].ColumnName;
        this.gvDDL.Columns.Add(tf);
        gvDDL.DataSource = dt;
        gvDDL.DataBind();
    }

}
public class CreateDropDownList:ITemplate
 {
    string checkboxID;
    public CreateDropDownList(string id)
    {
        this.checkboxID = id;
        //
        // TODO: Add constructor logic here
        //
    }
    public void InstantiateIn(Control container)
    {
        DropDownList ddl = new DropDownList();
        ddl.ID = checkboxID;
        container.Controls.Add(ddl);
    }
 }

Please try this piece of code. This way you can add a drop down list at run time without defining it in the aspx page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top