views:

311

answers:

2

I'm quite new to the C# combo with ASP.NET, so i'll try to be as clear as i can with my explanation.

I'm using a GridView to display some columns and rows that reside in a database. This works excellent. Because i wanted to add columns dynamically out of a List of names. Let's say we have a list with 5 names in it, then it dynamically creates a column for every name in the GridView. Here's some code to display what i do:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //Create columns for each student
        List<Student> allStudents = new Eetlijst.Business.Students().GetAll();
        allStudents.Reverse();

        foreach (Student student in allStudents)
        {
            StudentBoundField studentField = new StudentBoundField();
            studentField.HeaderText = student.Naam;
            MaaltijdGrid.Columns.Insert(4, studentField);
        }

        ShowDataInGrid(DateTime.Now.Month, DateTime.Now.Year);

There's some other stuff in there that isn't important. The ShowDataInGrid looks as following:

public void ShowDataInGrid(int maand, int jaar)
{
    List<Maaltijd> allMaaltijden = new Eetlijst.Business.Maaltijden().GetByMonthAndYear(maand, jaar);
    Session.Contents.Add("maaltijden", allMaaltijden);

    MaaltijdGrid.DataSource = allMaaltijden;
    MaaltijdGrid.DataBind();
}

How do i create the dynamic columns for each row? I create them with a DataBound event. So when the GridView databinds, the columns get filled with data. There is also a check inside to see if the row is in edit mode or not. So when i click on the edit button next to the row, the row goes perfectly in edit mode. The code i made adds a TextBox control to the cell. When i fill in a value and press the Update button, it can't find any controls anymore and therefore i can't get the value i entered. The control is still there in the DataBound when i put a break point after it. But as soon as i click the Update button, all the controls of the cells are gone.

I searched on the internet and all i found is that it has something to do with the application firing a postback before it reaches the RowUpdating method.

So, how can i let the controls exist that i added to the cell when it is in edit mode?

If anyone needs the code that's inside the DataBound event i'll post it.

A: 

Hey,

Dynamic controls or columns need to be recreated on every page load, because of the way that controls work. Dynamic controls do not get retained so you have to reload them on every page postback; however, viewstate will be retained for these controls.

HTH.

Brian
A: 

Hi,

Call this function ShowDataInGrid(DateTime.Now.Month, DateTime.Now.Year); in your

Page_Init event.

You will get the control and also the value.

Geetha