DataGrid+DropDownList绑定已没问题,如何实现在编辑这一行时,DropDownList可以停在数据库里数据所处的位置?
Sub MyDataGrid_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles MyDataGrid.ItemDataBound
Dim mg as new ManageDB
Dim DS as DataSet
DS=mg.GetCompanyByID(MyDataGrid.DataKeys(Cint(E.Item.ItemIndex)))
If e.Item.ItemType = ListItemType.EditItem Then
Dim myDropDownList As New DropDownList
myDropDownList = CType(e.Item.FindControl( "ddlCompanyArea "), DropDownList)
myDropDownList.DataSource = BindCompanyArea()
myDropDownList.DataTextField = "Company_Area "
myDropDownList.DatavalueField = "ID "
myDropDownList.DataBind()
myDropDownList.SelectedIndex=myDropDownList.Items.IndexOf(myDropDownList.Items.FindbyValue(DS.Tables(0).ROWS(0).Item( "id_company_area ").ToString))
End If
End Sub
我认为问题在这一句
mg.GetCompanyByID(MyDataGrid.DataKeys(Cint(E.Item.ItemIndex)))
E.Item.ItemIndex取出值是-1,MyDataGrid.DataKeys出错
但不知道如何处理?
[解决办法]
E.Item.ItemIndex为-1时是DataGrid的头,为0时才是第一行,
你把代码放到if(E.Item.ItemIndex != -1)中应该能解决
[解决办法]
DataRowView rowitem = (DataRowView)e.Row.DataItem;
DropDownList clsname = (DropDownList)e.Row.FindControl( "uclassname ");
if (rowitem[ "ClassName "] != DBNull.Value)
{
clsname.Items.FindByText(rowitem[ "ClassName "].ToString()).Selected = true;
}