Ошибка построения диалога :: динамическое создание столбцов шаблона динамически в виде сетки 2.0 - PullRequest
0 голосов
/ 02 февраля 2012

Эта ссылка была моей ссылкой (код проекта): динамически создавать столбцы шаблонов в виде сетки

Мои потребности: Чтобы построить сетку, в которой иногда есть 2 столбца шаблона радиокнопки и нескольков два раза больше, чем в отношении вопросов к базе данных.

Каждый раз, когда я захожу на страницу, эта сетка будет иметь следующие примеры:

  • 2-4 вопроса с 2 переключателями параметров.
  • 2-7 вопросов с 5-ю опциональными переключателями.

Ошибка сборки

Cannot implicitly convert type GridViewTemplate' to 'System.Web.UI.WebControls.TemplateField'

Мой класс:

public class GridViewTemplate : ITemplate
{
    #region Members
    //A variable to hold the type of ListItemType.
    ListItemType litTemplateType;

    //A variable to hold the column name.
    string sColumnName;

    //A variable to hold the Template Field Control type.
    string sItemControlType;
    #endregion

    #region Constructor
    /// <summary>
    /// Constructor where we define the template type, column name and control type.
    /// </summary>
    /// <param name="litType">ListItemType template type</param>
    /// <param name="sColName">string column name</param>
    public GridViewTemplate(ListItemType litType, string sColName)
    {
        //Stores the template type.
        litTemplateType = litType;

        //Stores the column name.
        sColumnName = sColName;
    }
    /// <summary>
    /// Constructor where we define the template type, column name and control type.
    /// </summary>
    /// <param name="litType">ListItemType template type</param>
    /// <param name="sColName">string column name</param>
    /// <param name="sControlType">string control type</param>
    public GridViewTemplate(ListItemType litType, string sColName, string sControlType)
    {
        //Stores the template type.
        litTemplateType = litType;

        //Stores the column name.
        sColumnName = sColName;

        //Stores the template field control type.
        sItemControlType = sControlType;
    }
    #endregion

    void ITemplate.InstantiateIn(System.Web.UI.Control oContainer)
    {
        switch (litTemplateType)
        {
            case ListItemType.Header:
                //Creates a new label control and add it to the container.
                Label lblHeaderText = new Label();                          //Allocates the new label object.
                lblHeaderText.Text = sColumnName;                           //Assigns the name of the column in the lable.
                oContainer.Controls.Add(lblHeaderText);                     //Adds the newly created label control to the container.
                break;

            case ListItemType.Item:
                //Creates a new text box control and add it to the container.
                switch (sItemControlType.ToUpper())
                {
                    case "TEXTBOX":
                        TextBox tb1 = new TextBox();                                //Allocates the new text box object.
                        tb1.DataBinding += new EventHandler(tb1_DataBinding);       //Attaches the data binding event.
                        tb1.Columns = 4;                                            //Creates a column with size 4.
                        oContainer.Controls.Add(tb1);                               //Adds the newly created textbox to the container.
                        break;
                    case "RADIOBUTTON":
                        RadioButton rbtnItem = new RadioButton();                           //Allocates the new text box object.
                        rbtnItem.DataBinding += new EventHandler(rbtnItem_DataBinding);     //Attaches the data binding event.
                        oContainer.Controls.Add(rbtnItem);                                  //Adds the newly created textbox to the container.
                        break;
                }
                break;

            case ListItemType.EditItem:
                //As, I am not using any EditItem, I didn't added any code here.
                break;

            case ListItemType.Footer:
                //As, I am not using any EditItem, I didn't added any code here.
                break;
        }
    }

    /// <summary>
    /// This is the event, which will be raised when the binding happens.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void tb1_DataBinding(object sender, EventArgs e)
    {
        TextBox txtdata = (TextBox)sender;
        GridViewRow container = (GridViewRow)txtdata.NamingContainer;
        object dataValue = DataBinder.Eval(container.DataItem, sColumnName);
        if (dataValue != DBNull.Value)
        {
            txtdata.Text = dataValue.ToString();
        }
    }
    #region Event :: Radio Button Data Binder
    /// <summary>
    /// This is the event, which will be raised when the binding happens.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void rbtnItem_DataBinding(object sender, EventArgs e)
    {
        RadioButton rbtnItem = (RadioButton)sender;
        GridViewRow oRowContainer = (GridViewRow)rbtnItem.NamingContainer;
        object oDataValue = DataBinder.Eval(oRowContainer.DataItem, sColumnName);
        if (oDataValue != DBNull.Value)
        {
            bool bValue;
            bool bIsValid;
            bIsValid = bool.TryParse(oDataValue.ToString(), out bValue);
            if (bIsValid)
                rbtnItem.Checked = (bool)oDataValue;
            else
                rbtnItem.Checked = false;
        }
    }
    #endregion
}

и метод Cols сетки построения:

private void vBuildGridColumns()
    {
        BoundField bfldQuestionDesc = new BoundField();
        bfldQuestionDesc.DataField = "Question_Desc";
        bfldQuestionDesc.HeaderText = "Question";// GetLocalResourceObject("Col1_Text").ToString();
        bfldQuestionDesc.SortExpression = "Question_DescArabic";

        gvEvaluation.Columns.Add(bfldQuestionDesc);

        DataTable dtData = dtGetEvaluationGridColumns();
        if (dtData != null && dtData.Rows.Count > 0)
        {
            TemplateField tfldRadio;
            for (int i = 0; i < dtData.Rows.Count; i++)
            {
                tfldRadio = new TemplateField();
                tfldRadio = new GridViewTemplate(ListItemType.Header, dtData.Rows[i]["Answer_Desc"].ToString());
                tfldRadio = new GridViewTemplate(ListItemType.Item, dtData.Rows[i]["Answer_Desc"].ToString(),"RadioButton");
                gvEvaluation.Controls.Add(tfldRadio);
            }
        }
    }

1 Ответ

1 голос
/ 06 февраля 2012

Я продолжал поиск, и все пользовательские динамические шаблоны создавались одинаково.

Я рассчитывал на следующее:

До:

tfldRadio = new TemplateField();
            tfldRadio = new GridViewTemplate(ListItemType.Header, dtData.Rows[i]["Answer_Desc"].ToString());
            tfldRadio = new GridViewTemplate(ListItemType.Item, dtData.Rows[i]["Answer_Desc"].ToString(),"RadioButton");
            gvEvaluation.Controls.Add(tfldRadio);

Исправлено:

for (int i = 0; i < dtData.Rows.Count; i++)
            {
                tfldRadio = new TemplateField();
                tfldRadio.HeaderTemplate = new GridViewTemplate(ListItemType.Header, dtData.Rows[i]["Answer_Desc_Arabic"].ToString());
                tfldRadio.ItemTemplate = new GridViewTemplate(ListItemType.Item, "Answer_ID", "RadioButton");
                gvEvaluation.Columns.Insert(i + 1, tfldRadio);
            }

Было просто, что я не заметил, что мне нужно определить HeaderTemplate и ItemTemplates my bad:)

...