Creating a gridview programmatically is easy. All you have to do is create the GridView object, bind data and add it to the page like this:
Dim GridView1 As New GridView
GridView1.DataSource = MyDataTable
GridView1.DataBind
MyPlaceholder.Controls.Add(GridView1)
This will give you a basic grid view that will provide textbox controls in the fields when the grid view is set to edit mode. If you drop a gridView object on a page, you will get the same results. In the codebehind, you would only have to use these lines:
GridView1.DataSource = MyDataTable
GridView1.DataBind
But, if you want to create a drop down list instead of a textbox in the gridview you can easily do this. Click on the smart tag for the gridview and go to click on "Edit Columns". Find the column that you want to change from a textbox and click on "Convert this field into a TemplateField".
Close the box and return to the smart tag options and click on "Edit Templates" Any columns that you have turned into templateFields will show up as on option in the new view (you may have to click on the smart tag again). Each templated column will have a view for the Item {read only/default view}, Edit {what you see when the grid view is in edit mode...you can make things read only, or invisible here if you don't want them to be seen in edit mode}, also templates for Insert {insert view of the gridview insert mode}, the Footer and Header also.
So, if you want to see a dropdownlist instead of a text box in the Item template for example, you can simply delete the text box. Replace it with a dropdownlist control, rebind the new control to the correct field (the control will have its own smart tag that says, "Edit Databindings"). Name the new control if you want to access it programmatically.
For this example, will name it DropDownList1 (original, yes, I know
. So, in the code behind if you want to be able to access the information in that dropdownlist you could do the following:
Dim myDDL as DropDownList = CType(Me.GridView1.FindControl("DropDownList1"), DropDownList)
If Not myDDL is Nothing Then
myDDL.text = "Something I want it to say"
End If
As a note: you can add anything you want in these template fields. You can add a detailsView, FormView, whatever. You would access them programatically the same way. (me.gridview1.findcontrol("controlname")) then, you can access them. HINT: If you need to access a template field in a formview, for example, that is nested in a gridview template field you first need to "FindControl" the formview...then "FindControl" again the formview control.