2013-09-18 3 views
2

Как я могу выделить столбец «DurationType» в моем коде в раскрывающемся меню?Выпадающее меню в RadGrid

Я уже изменил код, чтобы показать, как создать шаблон и добавить раскрывающийся список. Но я не могу понять, как получить значение раскрывающегося списка, и только для него отображаться в шаблонах insert/edit, а не в обычной сетке.

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (Session["GridData"] == null) 
    { 
     DataTable table = GetTable(); 
     Session.Add("GridData", table); 
    } 
    DefineGridStructure(); 
} 

public class MyTemplate : ITemplate 
{ 
    protected DropDownList dl; 
    private string colname; 

    public MyTemplate(string cName) 
    { 
     colname = cName; 
    } 

    public void InstantiateIn(System.Web.UI.Control container) 
    { 
     dl = new DropDownList(); 
     dl.ID = colname; 
     dl.Items.Add(new ListItem("Hours", "Hours")); 
     dl.Items.Add(new ListItem("Days", "Days")); 
     dl.Items.Add(new ListItem("Weeks", "Weeks")); 
     dl.Items.Add(new ListItem("Months", "Months")); 
     container.Controls.Add(dl); 
    } 

    void boolValue_DataBinding(object sender, EventArgs e) 
    { 
     DropDownList cBox = (DropDownList)sender; 
     GridDataItem container = (GridDataItem)cBox.NamingContainer; 
    } 
} 

private void DefineGridStructure() 
{ 
    RadGrid grid = new RadGrid(); 
    grid.ID = "RadGrid1"; 
    grid.NeedDataSource += new GridNeedDataSourceEventHandler(grid_NeedDataSource); 
    grid.AutoGenerateEditColumn = true; 
    grid.AutoGenerateDeleteColumn = true; 
    grid.AllowAutomaticInserts = false; 
    grid.Width = Unit.Percentage(100); 
    grid.PageSize = 15; 
    grid.AllowPaging = true; 
    grid.PagerStyle.Mode = GridPagerMode.NextPrevAndNumeric; 
    grid.AutoGenerateColumns = false; 
    grid.MasterTableView.Width = Unit.Percentage(100); 
    grid.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.TopAndBottom; 
    grid.AllowAutomaticDeletes = false; 
    grid.AllowAutomaticUpdates = false; 
    grid.InsertCommand +=grid_InsertCommand; 
    grid.MasterTableView.DataKeyNames = new string[] { "RowNumber" }; 
    GridBoundColumn boundColumn = new GridBoundColumn(); 
    boundColumn.DataField = "RowNumber"; 
    boundColumn.HeaderText = "RowNumber"; 
    boundColumn.ReadOnly = true; 
    grid.MasterTableView.Columns.Add(boundColumn); 
    boundColumn = new GridBoundColumn(); 
    boundColumn.DataField = "Size"; 
    boundColumn.HeaderText = "Size"; 
    grid.MasterTableView.Columns.Add(boundColumn); 
    boundColumn = new GridBoundColumn(); 
    boundColumn.DataField = "Description"; 
    boundColumn.HeaderText = "Description"; 
    grid.MasterTableView.Columns.Add(boundColumn); 
    boundColumn = new GridBoundColumn(); 
    boundColumn.DataField = "Quantity"; 
    boundColumn.HeaderText = "Quantity"; 
    grid.MasterTableView.Columns.Add(boundColumn); 
    boundColumn = new GridBoundColumn(); 
    boundColumn.DataField = "Duration"; 
    boundColumn.HeaderText = "Duration"; 
    grid.MasterTableView.Columns.Add(boundColumn); 
    boundColumn = new GridBoundColumn(); 
    // Added code snippet to create the dropdown list 
    GridTemplateColumn objGridTemplateColumn = new GridTemplateColumn(); 
    objGridTemplateColumn.HeaderText = "DurationType"; 
    objGridTemplateColumn.UniqueName = "DurationType"; 
    objGridTemplateColumn.ItemTemplate = new MyTemplate("DurationType"); 
    grid.MasterTableView.Columns.Add(objGridTemplateColumn); 
    boundColumn = new GridBoundColumn(); 
    boundColumn.DataField = "Amount"; 
    boundColumn.HeaderText = "Amount"; 
    grid.MasterTableView.Columns.Add(boundColumn); 
    PlaceHolder1.Controls.Add(grid); 
} 

private void grid_InsertCommand(object sender, GridCommandEventArgs e) 
{ 
    // Looking to loop through the form so i can insert the values into the datatable 
} 

void grid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e) 
{ 
    DataTable current = (DataTable)Session["GridData"]; 
    RadGrid grid = (RadGrid)sender; 
    grid.DataSource = current; 
} 

static DataTable GetTable() 
{ 
    // 
    // Here we create a DataTable with a few columns. 
    // 
    // Create Datatable to store all colums 
    DataTable dt = new DataTable(); 
    DataRow dr = null; 
    dt.Columns.Add(new DataColumn("RowNumber", typeof(string))); 
    dt.Columns.Add(new DataColumn("Size", typeof(string))); 
    dt.Columns.Add(new DataColumn("Description", typeof(string))); 
    dt.Columns.Add(new DataColumn("Quantity", typeof(string))); 
    dt.Columns.Add(new DataColumn("Unit", typeof(string))); 
    dt.Columns.Add(new DataColumn("Duration", typeof(string))); 
    dt.Columns.Add(new DataColumn("DurationType", typeof(string))); 
    dt.Columns.Add(new DataColumn("Amount", typeof(string))); 
    dr = dt.NewRow(); 
    dr["RowNumber"] = 1; 
    dr["Size"] = string.Empty; 
    dr["Description"] = string.Empty; 
    dr["Quantity"] = string.Empty; 
    dr["Unit"] = string.Empty; 
    dr["Duration"] = string.Empty; 
    dr["DurationType"] = string.Empty; 
    dr["Amount"] = string.Empty; 
    dt.Rows.Add(dr); 
    return dt; 
} 
+0

Я изменил код и добавил раздел, чтобы создать шаблон с каплей вниз и добавил выпадающее меню в колонке DurationType. Теперь, когда я загружаю страницу, я вижу выпадающий список, , но я не могу понять, как получить выбранное значение здесь, и если я обновляю код, я хочу убедиться, что при выгрузке загружается его нужный элемент выбран. Также как я могу сделать фактическую выпадающую нагрузку только в шаблоне вставки или редактирования, и когда она отображает фактическую сетку, чтобы показать ее как текст? –

+0

Я смог использовать это, чтобы получить значение, но он получает только один из них, и я не могу указать, какую строку посмотреть на него string text = (e.Item.FindControl («DurationType») как DropDownList) .SelectedValue ; –

+0

Любая помощь, пожалуйста, сходит с ума, пытаясь заставить ее работать. –

ответ

0

В существующем коде, я редактировал несколько строк, чтобы заменить DropDownList с Telerik RadComboBox. В основном, что я делаю, когда сетка находится в режиме редактирования, я получаю существующие привязки текста из события сетки, а затем привязываю все новые данные к RadCombobox, окончательно устанавливая выбранное поле как таковое, которое Я попадаю на мероприятие.

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (Session["GridData"] == null) 
    { 
     DataTable table = GetTable(); 
     Session.Add("GridData", table); 
    } 
    DefineGridStructure(); 
} 

public class MyTemplate : ITemplate 
{ 
    protected RadComboBox dl; 
    private string colname; 

    public MyTemplate(string cName) 
    { 
     colname = cName; 
    } 

    public void InstantiateIn(System.Web.UI.Control container) 
    { 
     dl = new RadComboBox(); 
     dl.ID = colname; 
     dl.DataSource=getDurationTypes(); 

     dl.DataTextField = "DurationTypeName"; 
     dl.DataValueField = "DurationTypeID"; 
     dl.DataBind();    
     container.Controls.Add(dl); 
    } 

    void boolValue_DataBinding(object sender, EventArgs e) 
    { 
     RadComboBox cBox = (RadComboBox)sender; 
     GridDataItem container = (GridDataItem)cBox.NamingContainer; 
    } 
} 

private void DefineGridStructure() 
{ 
    RadGrid grid = new RadGrid(); 
    grid.ID = "RadGrid1"; 
    grid.NeedDataSource += new GridNeedDataSourceEventHandler(grid_NeedDataSource); 
    grid.ItemDataBound +=new GridItemEventHandler(); 
    grid.AutoGenerateEditColumn = true; 
    grid.AutoGenerateDeleteColumn = true; 
    grid.AllowAutomaticInserts = false; 
    grid.Width = Unit.Percentage(100); 
    grid.PageSize = 15; 
    grid.AllowPaging = true; 
    grid.PagerStyle.Mode = GridPagerMode.NextPrevAndNumeric; 
    grid.AutoGenerateColumns = false; 
    grid.MasterTableView.Width = Unit.Percentage(100); 
    grid.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.TopAndBottom; 
    grid.AllowAutomaticDeletes = false; 
    grid.AllowAutomaticUpdates = false; 
    grid.InsertCommand +=grid_InsertCommand; 
    grid.MasterTableView.DataKeyNames = new string[] { "RowNumber" }; 
    GridBoundColumn boundColumn = new GridBoundColumn(); 
    boundColumn.DataField = "RowNumber"; 
    boundColumn.HeaderText = "RowNumber"; 
    boundColumn.ReadOnly = true; 
    grid.MasterTableView.Columns.Add(boundColumn); 
    boundColumn = new GridBoundColumn(); 
    boundColumn.DataField = "Size"; 
    boundColumn.HeaderText = "Size"; 
    grid.MasterTableView.Columns.Add(boundColumn); 
    boundColumn = new GridBoundColumn(); 
    boundColumn.DataField = "Description"; 
    boundColumn.HeaderText = "Description"; 
    grid.MasterTableView.Columns.Add(boundColumn); 
    boundColumn = new GridBoundColumn(); 
    boundColumn.DataField = "Quantity"; 
    boundColumn.HeaderText = "Quantity"; 
    grid.MasterTableView.Columns.Add(boundColumn); 
    boundColumn = new GridBoundColumn(); 
    boundColumn.DataField = "Duration"; 
    boundColumn.HeaderText = "Duration"; 
    grid.MasterTableView.Columns.Add(boundColumn); 
    boundColumn = new GridBoundColumn(); 
    // Added code snippet to create the dropdown list 
    GridTemplateColumn objGridTemplateColumn = new GridTemplateColumn(); 
    objGridTemplateColumn.HeaderText = "DurationType"; 
    objGridTemplateColumn.UniqueName = "DurationType"; 
    objGridTemplateColumn.ItemTemplate = new MyTemplate("DurationType"); 
    grid.MasterTableView.Columns.Add(objGridTemplateColumn); 
    boundColumn = new GridBoundColumn(); 
    boundColumn.DataField = "Amount"; 
    boundColumn.HeaderText = "Amount"; 
    grid.MasterTableView.Columns.Add(boundColumn); 
    PlaceHolder1.Controls.Add(grid); 
} 

private void grid_InsertCommand(object sender, GridCommandEventArgs e) 
{ 
    // Looking to loop through the form so i can insert the values into the datatable 
} 

void grid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e) 
{ 
    DataTable current = (DataTable)Session["GridData"]; 
    RadGrid grid = (RadGrid)sender; 
    grid.DataSource = current; 
} 

static DataTable GetTable() 
{ 
    // 
    // Here we create a DataTable with a few columns. 
    // 
    // Create Datatable to store all colums 
    DataTable dt = new DataTable(); 
    DataRow dr = null; 
    dt.Columns.Add(new DataColumn("RowNumber", typeof(string))); 
    dt.Columns.Add(new DataColumn("Size", typeof(string))); 
    dt.Columns.Add(new DataColumn("Description", typeof(string))); 
    dt.Columns.Add(new DataColumn("Quantity", typeof(string))); 
    dt.Columns.Add(new DataColumn("Unit", typeof(string))); 
    dt.Columns.Add(new DataColumn("Duration", typeof(string))); 
    dt.Columns.Add(new DataColumn("DurationType", typeof(string))); 
    dt.Columns.Add(new DataColumn("Amount", typeof(string))); 
    dr = dt.NewRow(); 
    dr["RowNumber"] = 1; 
    dr["Size"] = string.Empty; 
    dr["Description"] = string.Empty; 
    dr["Quantity"] = string.Empty; 
    dr["Unit"] = string.Empty; 
    dr["Duration"] = string.Empty; 
    dr["DurationType"] = string.Empty; 
    dr["Amount"] = string.Empty; 
    dt.Rows.Add(dr); 
    return dt; 
} 

ItemDataBound событие для отображения ItemTemplate, когда он находится в режиме редактирования, RadcomboBox появится, когда решетка находится в режиме редактирования.

protected void Grid_ItemDataBound(object sender, GridItemEventArgs e) 
    { 
    string DurationName; 
    if (e.Item is GridDataItem) 
    { 
     GridDataItem myGridItem = (GridDataItem)e.Item; 
     //Changing the DurationName field to Combobox in EDITMODE 
     if (myGridItem.IsInEditMode) 
     { 
      GridEditableItem edititem = e.Item as GridEditableItem; 
      int userId = Convert.ToInt16(edititem.GetDataKeyValue("RowNumber")); 
      RadComboBoxItem selectedItem = new RadComboBoxItem(); 
      RadComboBox combo = (RadComboBox)myGridItem["DurationType"].FindControl("colname"); 
      DurationName= DataBinder.Eval(myGridItem.DataItem, "DurationType").ToString(); 
      combo.DataSource = roles.GetRoles(); 
      combo.DataTextField = "DurationType"; 
      combo.DataValueField = "DurationID"; 
      combo.DataBind(); 
      selectedItem = combo.FindItemByText(DurationName); 
      combo.SelectedIndex = selectedItem.Index; 
     } 
     } 
    } 

Этот метод возвращает данные для его связывания с radcombobox (DropDownList)

private DataTable getDurationTypes() 
{ 
    DataTable table = new DataTable(); 
    table.Columns.Add("DurationTypeID", typeof(int)); 
    table.Columns.Add("DurationTypeName", typeof(string)); 
    table.Rows.Add(1, "Hours"); 
    table.Rows.Add(2, "Days"); 
    table.Rows.Add(3, "Weeks"); 
    table.Rows.Add(4, "Months"); 
    return table; 
} 
Смежные вопросы