Динамически добавленные элементы управления отсутствуют во время GridView RowUpdating - PullRequest
1 голос
/ 07 февраля 2012

У меня есть GridView со столбцом TemplateField, в который я поместил элементы управления PlaceHolder. Во время события DataBound для GridView я динамически добавляю несколько флажков в PlaceHolder. Это прекрасно работает и отображает как ожидалось.

Моя проблема в том, что во время события RowUpdating PlaceHolder не содержит элементов управления; мои флажки отсутствуют. Я также заметил, что они отсутствуют во время события RowEditing.

Я хочу иметь возможность получать значения CheckBoxes во время события RowUpdating, чтобы я мог сохранить их в базе данных.

Вот пример кода. Я много обрезал, чтобы уменьшить размер, но если вы хотите увидеть подробности, просто спросите, и я буду рад добавить больше.

HTML:

<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False" 
    ondatabound="gridView_DataBound" onrowupdating="gridView_RowUpdating" 
    onrowediting="gridView_RowEditing" DataKeyNames="ID">
    <Columns>
        <asp:TemplateField HeaderText="Countries">
            <ItemTemplate>
                <asp:PlaceHolder ID="countriesPlaceHolder" runat="server"></asp:PlaceHolder>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:PlaceHolder ID="countriesPlaceHolder" runat="server"></asp:PlaceHolder>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField ShowHeader="False">
            <ItemTemplate>
                <asp:LinkButton ID="editButton" runat="server" CommandName="Edit" Text="Edit"></asp:LinkButton>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:LinkButton ID="updateButton" runat="server" CommandName="Update" Text="Update"></asp:LinkButton>
            </EditItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Код:

// This method works fine, no obvious problems here.
protected void gridView_DataBound(object sender, EventArgs e)
{
    // Loop through the Holidays that are bound to the GridView
    var holidays = (IEnumerable<Holiday>)gridView.DataSource;
    for (int i = 0; i < holidays.Count(); i++)
    {
        // Get the row the Holiday is bound to
        GridViewRow row = gridView.Rows[i];
        // Get the PlaceHolder control
        var placeHolder = (PlaceHolder)row.FindControl("countriesPlaceHolder");
        // Create a CheckBox for each country and add it to the PlaceHolder
        foreach (Country country in this.Countries)
        {
            bool isChecked = holidays.ElementAt(i).Countries.Any(item => item.ID == country.ID);
            var countryCheckBox = new CheckBox
            {
                Checked = isChecked,
                ID = country.Abbreviation + "CheckBox",
                Text = country.Abbreviation
            };
            placeHolder.Controls.Add(countryCheckBox);
        }
    }
}

protected void gridView_RowEditing(object sender, GridViewEditEventArgs e)
{
    // EXAMPLE: I'm expecting checkBoxControls to contain my CheckBoxes, but it's empty.
    var checkBoxControls = gridView.Rows[e.NewEditIndex].FindControl("countriesPlaceHolder").Controls;

    gridView.EditIndex = e.NewEditIndex;
    BindData();
}

protected void gridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    // EXAMPLE: I'm expecting checkBoxControls to contain my CheckBoxes, but it's empty.
    var checkBoxControls = ((PlaceHolder)gridView.Rows[e.RowIndex].FindControl("countriesPlaceHolder")).Controls;

    // This is where I'd grab the values from the controls, create an entity, and save the entity to the database.

    gridView.EditIndex = -1;
    BindData();
}

Это статья, которой я следовал для моего подхода к привязке данных: http://www.aarongoldenthal.com/post/2009/04/19/Manually-Databinding-a-GridView.aspx

1 Ответ

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

Вам нужно вызвать ваш метод BindData () при загрузке страницы.

"Динамические элементы управления или столбцы необходимо воссоздавать при каждой загрузке страницы из-за способа работы элементов управления. Динамические элементы управления не сохраняются, поэтому вам придется перезагружать их при каждой обратной передаче страницы, однако для них будет сохраняться представление состояния. контроль ".

См. Ячейки в gridview теряют контроль над событием RowUpdating

Также в статье, на которую вы ссылаетесь, есть ItemTemplate и EditItemTemplace, потому что они имеют разные дисплеи, то есть только для чтения и доступны для редактирования. Вы такие же, я думаю, вы могли бы упростить свой дизайн:

<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" ondatabound="gridView_DataBound">
<Columns>
    <asp:TemplateField HeaderText="Countries">
        <ItemTemplate>
            <asp:PlaceHolder ID="countriesPlaceHolder" runat="server"></asp:PlaceHolder>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField ShowHeader="False">
        <ItemTemplate>
            <asp:LinkButton ID="editButton" runat="server" Text="Edit" onclick="editButton_Click" ></asp:LinkButton>
            <asp:LinkButton ID="updateButton" runat="server" Text="Update" onclick="updateButton_Click" ></asp:LinkButton>
        </ItemTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>

Код сзади:

    protected void gridView_DataBound(object sender, EventArgs e)
    {
        // Loop through the Holidays that are bound to the GridView
        var holidays = (IEnumerable<Holiday>)gridView.DataSource;
        for (int i = 0; i < holidays.Count(); i++)
        {
            // Get the row the Holiday is bound to
            GridViewRow row = gridView.Rows[i];
            // Get the PlaceHolder control
            var placeHolder = (PlaceHolder) row.FindControl("countriesPlaceHolder");
            var countryCheckBox = new CheckBox
                                      {
                                          Checked = true,
                                          ID = "auCheckBox",
                                          Text = "Aus",
                                          Enabled = false
                                      };
            placeHolder.Controls.Add(countryCheckBox);

            var editButton = (LinkButton)row.FindControl("editButton");
            editButton.CommandArgument = i.ToString();
            var updateButton = (LinkButton)row.FindControl("updateButton");
            updateButton.CommandArgument = i.ToString();
            updateButton.Visible = false;
        }
    }

    protected void editButton_Click(object sender, EventArgs e)
    {
        LinkButton editButton = (LinkButton) sender;
        int index = Convert.ToInt32(editButton.CommandArgument);

        GridViewRow row = gridView.Rows[index];
        // Get the PlaceHolder control
        LinkButton updateButton = (LinkButton)row.FindControl("updateButton");
        updateButton.Visible = true;
        editButton.Visible = false;

        CheckBox checkbox = (CheckBox)row.FindControl("auCheckBox");
        if (checkbox != null)
        {
            checkbox.Enabled = true;
            // Get value and update
        }
    }

    protected void updateButton_Click(object sender, EventArgs e)
    {
        LinkButton updateButton = (LinkButton)sender;
        int index = Convert.ToInt32(updateButton.CommandArgument);

        GridViewRow row = gridView.Rows[index];
        // Get the PlaceHolder control
        LinkButton editButton = (LinkButton)row.FindControl("updateButton");
        editButton.Visible = true;
        updateButton.Visible = false;

        CheckBox checkbox = (CheckBox)row.FindControl("auCheckBox");
        if (checkbox != null)
        {
            // Get value and update

            checkbox.Enabled = false;
        }
    }

Если вы хотите, чтобы он был включен с самого начала, просто удалите включенные проверки, и вы можете удалить свою кнопку редактирования.

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...