Simple use of template columns to bind DropDownList, beginners must have, but sometimes, what we have to do is to make a column to DropDownList when editing, and automatically transform DropDownList according to the value displayed under normal circumstances Value, then save the selected value to the database or XML file, actually to do such a function, as long as we learn to use the DataGrid DataGrid1_itemdatabase event, let me do an example.
// Retrieve the function of the database public Dataset getzcbd () {DataSet DS = new dataset (); string searchString = "SELECT ID, YY, BJ from ZC"; da = new oledbdataadapter (searchString, conn); da.fill DS, "yy"); return ds;} catCh {return null;}}
// Bind DataGrid Private Void BindGrid () {DataSet DS = New Dataset (); DS = US.Getzcbd (); if (DS! = Null) {this.dataGrid1.datasource = DS; this.DataGrid1.Database Else {msg.alert ("Load Data Error!", Page);}} After the DataGrid is bound, set the template column, let it display it under normal display, and bound to a ID value in the database, In the editing state, it is DROPDOWNLIST, and bound to a name value in the database. We must do now is that when we choose to edit, the name is automatically obtained from the database according to the value of the Label, and use the DropDownList default. (Note: In order to facilitate everyone to learn, I give an example of a simple code for your reference)
private void DataGrid1_ItemDataBound (object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) {if (e.Item.ItemType == ListItemType.EditItem) {DataRowView drv = (DataRowView) e.Item.DataItem; string current = drv [ "label1"]. TOSTRING (); DropDownList DDL = (DropdownList) E.Item.FindControl ("DDL"); ddl.selectedIndex = DDL.Items.indexof (ddl.Items.FindByValue (current));} IF E.Item.itemType == ListiteMTYPE.Item) || (E.Item.ItemType == ListItemType.AlternatingItem) {Label T = (System.Web.ui.WebControls.Label) E.Item.FindControl ("label1" ); String current = this.bindddl (int.parse (t.text)); E.Item.cells [1] .text = current;}} private string bindddl (int DDD) {string sss = ""; if ( DDD == 1) {sss = "Zhang 3"; Return SSS; Else {sss = "李 四"; Return SSS;}}
Note: MSG is a MessageBox dialog that is similar to WinForm, does not have to pay attention. Can use label.text instead