Динамические списки DropDown GridView - PullRequest
0 голосов
/ 01 февраля 2011

У меня есть сетка со следующими полями

ИД ЛЕКЦИИ, ИМЯ ЛЕКТОРА, СУБЪЕКТЫ и сетка содержат кнопки для вставки, редактирования и удаления. Что я Когда я нажимаю, нужно, чтобы столбцы РЕДАКТИРОВАТЬ СУБЪЕКТЫ должны содержать списки DROPDOWN для выбора предметов. если строка GridView не находится в режиме EDIT или INSERT, режим DROPDOWN не должен отображаться и отображать только предмет, преподаваемый лектором.

Ответы [ 2 ]

1 голос
/ 03 февраля 2011

Хитрость при выполнении такого рода привязки данных состоит в том, чтобы использовать два источника данных, один из которых содержит идентификатор лекции, имя лектора и идентификатор субъекта, а другой просто содержит список субъектов. Вы можете сделать это с помощью любого элемента управления DataSource - вот демонстрация с использованием SqlDataSource:

<!-- First data source is the main data source for the gridview -->
<asp:SqlDataSource runat="server" id="LectureDataSource" 
SelectCommand="SELECT l.LectureId, l.Lecturer, l.SubjectId, s.Subject FROM Lecture l INNER JOIN Subject s ON l.SubjectId = s.SubjectID" 
UpdateCommand="UPDATE Lecture SET Lecturer = @Lecturer, SubjectId = @SubjectId"
DeleteCommand="DELETE FROM Lecture WHERE LectureId = @LectureId" InsertCommand="INSERT INTO Lecture (Lecturer, SubjectId) VALUES (@Lecturer, @SubjectID)"
>
<DeleteParameters>
    <asp:ControlParameter ControlID="LectureGridView" Name="LectureId" 
        PropertyName="SelectedValue" />
</DeleteParameters>
<UpdateParameters>
    <asp:Parameter Name="Lecturer" />
    <asp:Parameter Name="SubjectId" />
</UpdateParameters>
</asp:SqlDataSource>

<!-- Second data source is the data source for the Subject dropdownlist -->
<asp:SqlDataSource runat="server" ID="SubjectDataSource"  
 SelectCommand="SELECT SubjectId, Subject FROM Subject ORDER BY SubjectId" />

<asp:GridView runat="server" AutoGenerateColumns="False" DataSourceID="LectureDataSource"
    ID="LectureGridView" DataKeyNames="LectureId" >
    <!-- Setting the DataKeyNames property allows us to delete by using the SelectedValue -->
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton Text="Edit" runat="server" CommandName="Edit" />&nbsp;
                <asp:LinkButton Text="Delete" runat="server" CommandName="Delete" />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:LinkButton Text="Update" runat="server" CommandName="Update" />
                <asp:LinkButton Text="Cancel" runat="server" CommandName="Cancel" />
            </EditItemTemplate>
            <ItemStyle HorizontalAlign="Center" />
        </asp:TemplateField>
        <asp:BoundField DataField="LectureId" HeaderText="Lecture Id" ReadOnly="true" />
        <asp:TemplateField HeaderText="Lecturer">
            <ItemTemplate>
                <asp:Label Text='<%# Bind("Lecturer") %>' runat="server" ID="LecturerLabel" />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="LecturerEditTextBox" runat="server" Text='<%# Bind("Lecturer") %>'></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <!-- The label is bound to the subject text field from the LectureDataSource -->
                <asp:Label ID="SubjectLabel" runat="server" Text='<%# Bind("Subject")  %>' />
            </ItemTemplate>
            <EditItemTemplate>
                <!-- In Edit mode the dropdownlist is bound to the SubjectDataSource, but we also set the text value from the LectureDataSource -->
                <asp:DropDownList ID="SubjectEditDropDownList" runat="server" DataSourceID="SubjectDataSource"
                    DataTextField="Subject" DataValueField="SubjectId" Text='<%# Bind("SubjectId") %>'>
                </asp:DropDownList>
            </EditItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
1 голос
/ 01 февраля 2011

Это можно сделать, сделав столбец SUBJECT шаблоном TemplateField, как показано ниже:

<asp:TemplateField Header="Subject">
                    <EditItemTemplate>
                        <asp:DropDownList ID="subjectDDl" runat="server"></asp:DropDownList>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="subjectLabel" runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>

Возможно, вы уже добавили столбцы ButtonField для вызова функций EDIT, INSERT и DELETE.

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