Доступ к содержимому TextBox в динамически создаваемом GridView - PullRequest
0 голосов
/ 01 декабря 2011

Я создал gridview динамически, который состоит из Textboxes и buttonfield, при событии команды строки из gridview я хочу получить доступ к содержимому textbox.я не могу получить доступ к текстовому полю, вот мой код

protected void FillGridListTollCollection()
    {
        TollCollectionBLLC tollcollectionBLLC = new TollCollectionBLLC();
        dataTable = tollcollectionBLLC.GetTollCollectionDetailsBLLC(187, 1, 1, "10/10/2011");

        //put the gridview into the placeholder to get the values of textboxes in gridview
        PlaceHolder1.Controls.Add(GridListTollColletion);


        foreach (DataColumn col in dataTable.Columns)
        {

            if (col.ToString() == "TollCollID")
            {
                BoundField bField = new BoundField();
                bField.HeaderText = "TollCollID";
                bField.DataField = "TollCollID";
                bField.Visible = false;
                GridListTollColletion.Columns.Add(bField);
                continue;
            }
            if (col.ToString() == "TollAmtApplicable")
            {
                BoundField bField = new BoundField();
                bField.HeaderText = "TollAmtApplicable";
                bField.DataField = "TollAmtApplicable";
                bField.Visible = false;
                GridListTollColletion.Columns.Add(bField);
                continue;
            }
            if (col.ToString() == "TollCollDesc")
            {
                BoundField bField = new BoundField();
                bField.HeaderText = "Transaction Types";
                bField.DataField = "TollCollDesc";
                GridListTollColletion.Columns.Add(bField);
                continue;
            }

            if (col.ToString() == "Total")
            {
                BoundField bField = new BoundField();
                bField.HeaderText = "Total";
                bField.DataField = "Total";
                GridListTollColletion.Columns.Add(bField);
                continue;
            }

            if (col.ToString().Contains("Rate"))
            {
                BoundField bField = new BoundField();
                bField.HeaderText = col.ToString();
                bField.DataField = col.ToString();
                bField.Visible = false;
                GridListTollColletion.Columns.Add(bField);
                continue;
            }

            //Declare the bound field and allocate memory for the bound field.
            TemplateField tfield = new TemplateField();

            //Initalize the DataField value.
            tfield.HeaderTemplate = new GridViewTemplate(ListItemType.Header, col.ColumnName);
            tfield.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            tfield.HeaderStyle.VerticalAlign = VerticalAlign.Middle;
            tfield.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            tfield.ItemStyle.VerticalAlign = VerticalAlign.Middle;

            //Initialize the HeaderText field value.
            tfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, col.ColumnName);

            //Add the newly created bound field to the GridView.
            GridListTollColletion.Columns.Add(tfield);

        }


    protected void GridListTollColletion_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int tempCarCount = 0;
 // here i am getting exception
       int.TryParse( ( (TextBox)GridListTollColletion.Rows[Convert.ToInt32(e.CommandArgument)].Cells[Convert.ToInt32(e.CommandArgument)].Controls[3]).Text , out tempCarCount);
}

открытый класс GridViewTemplate: ITemplate {// Переменная для хранения типа ListItemType.ListItemType _templateType;

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

//Constructor where we define the template type and column name.
public GridViewTemplate(ListItemType type, string colname)
{
    //Stores the template type.
    _templateType = type;

    //Stores the column name.
    _columnName = colname;
}

void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
    switch (_templateType)
    {
        case ListItemType.Header:
            //Creates a new label control and add it to the container.
            Label lbl = new Label();            //Allocates the new label object.
            lbl.Text = _columnName;             //Assigns the name of the column in the lable.

            container.Controls.Add(lbl);        //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.
            TextBox tb1 = new TextBox();                            //Allocates the new text box object.
              tb1.Width = 60;
              tb1.Height = 22;
              tb1.MaxLength = 50;
              tb1.ID = "v";
              //Creates a column with size 4.
              tb1.DataBinding += new EventHandler(tb1_DataBinding);   //Attaches the data binding event.
              tb1.Columns = 7;
            container.Controls.Add(tb1);

            //Adds the newly created textbox to the container.
            break;

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

        case ListItemType.Footer:
            CheckBox chkColumn = new CheckBox();
            chkColumn.ID = "Chk" + _columnName;
            container.Controls.Add(chkColumn);
            break;
    }
}

    public IOrderedDictionary ExtractValues(Control container)
    {
        OrderedDictionary dict = new OrderedDictionary();
        if (_templateType == ListItemType.Item)
        { string value = ((TextBox)container.FindControl("tb1" + _columnName)).Text;
            dict.Add(_columnName, value); }
        return dict;
    }

    void tb1_DataBinding(object sender, EventArgs e)
    {
        TextBox txtdata = (TextBox)sender;
        GridViewRow container = (GridViewRow)txtdata.NamingContainer;
        object dataValue = DataBinder.Eval(container.DataItem, _columnName);
        if (dataValue != DBNull.Value)
        {
            txtdata.Text = dataValue.ToString();
        }
    }



    public GridViewTemplate()
    {
        //
        // TODO: Add constructor logic here
        //
    }

}

Ответы [ 2 ]

0 голосов
/ 01 декабря 2011

Разве это не удобно, если вы связываете эти добавленные элементы управления с событием GridView.RowDataBound .
Проверьте это BindData to ITemplate для GridView в коде

Если вы следуете этой статье MSDN Как: динамически создавать шаблоны элементов управления веб-сервера ASP.NET , чтобы составить представление об этом, посмотрите этот фрагмент кода.

static void Item_DataBinding(object sender, System.EventArgs e)
{
    PlaceHolder ph = (PlaceHolder)sender;
    RepeaterItem ri = (RepeaterItem)ph.NamingContainer;
    Int32 item1Value = (Int32)DataBinder.Eval(ri.DataItem, "CategoryID");
    String item2Value = (String)DataBinder.Eval(ri.DataItem, "CategoryName");
    ((Label)ph.FindControl("item1")).Text = item1Value.ToString();
    ((Label)ph.FindControl("item2")).Text = item2Value;
}

У него есть Item_DataBinding метод static. Вы настраиваете эти вещи статически, поэтому проверьте эту статью, чтобы улучшить свой код.

В Редактировать шаблон я предлагаю вам использовать RowBound Event для обработки этих элементов управления ... там вы можете легко получить к ним доступ.

0 голосов
/ 01 декабря 2011

Шаблон применяется статически.Таким образом, вы не сможете получить доступ к элементу управления, как пытаетесь это сделать.

Попробуйте использовать -

var textbox = GridListTollColletion.FindControl(<yourtextbox>);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...