簡體   English   中英

遍歷對象中的屬性並填充它

[英]loop through properties in object and populate it

我試圖遍歷對象中的屬性並將其應用為字符串。

例如,要動態執行此操作將是:

Dim objAnswers As New DAL.Quiz.QuizAnswers
    With objAnswers
        .Question1 = "text1"
        .Question2 = "text2"
        .Question3 = "text3"
        .Question4 = "text4"
        .Question5 = "text5"
    End With

但是我試圖遍歷對象的屬性,然后像這樣應用它:

Dim objAnswers As New DAL.Quiz.QuizAnswers
    For Each rptItem As RepeaterItem In repeater1.Items
        Dim ddlAnswers As App_Controls_Forms_DropDownList = CType(rptItem.FindControl("DropDownList1"), App_Controls_Forms_DropDownList)
        For Each p As System.Reflection.PropertyInfo In objAnswers.GetType().GetProperties()
            If p.ToString.StartsWith("question") Then
                p = ddlAnswers.SelectedText
            End If
        Next
    Next

我正在嘗試使用中繼器中的下拉列表中的s填充對象的字符串。 這是我想用偽做的事情-對於轉發器中的每一行,從下拉列表中獲取文本並填充以“問題”開頭的對象屬性

謝謝您的幫助!

編輯:

Dim objAnswers As New DAL.Quiz.QuizAnswers
    For Each p As System.Reflection.PropertyInfo In objAnswers.GetType().GetProperties()
        For Each rptItem As RepeaterItem In repeater1.Items
            Dim ddlAnswers As App_Controls_Forms_DropDownList = CType(rptItem.FindControl("DropDownList1"), App_Controls_Forms_DropDownList)
            If p.ToString.StartsWith("Question") Then
                p.SetValue(objAnswers, ddlAnswers.SelectedText)
            End If
        Next
    Next

我不使用vb​​,因此某些名稱可能是錯誤的。 我將循環這些項目,找到單個匹配的屬性並將其設置如下:

Dim objAnswers As New DAL.Quiz.QuizAnswers
Dim i as Integer
For i = 0 To repeater1.Items.Length - 1
    Dim ddlAnswers As App_Controls_Forms_DropDownList = CType(repeater1.Items[i].FindControl("DropDownList1"), App_Controls_Forms_DropDownList)
    Dim p as System.Reflection.PropertyInfo = objAnswers.GetType().GetProperty("Question" & i + 1)
    p.SetValue(objAnswers, ddlAnswers.SelectedText)
Next

這是您兩個問題的(過度)簡化解決方案。

--DB structure
create table dbo.questions(
id int identity(1,1) primary key,
question nvarchar(100) not null,
correctAnswerId int null --single correct answer
)
go
create table dbo.answers(
id int identity(1,1) primary key,
questionId int not null,
answer nvarchar(100) not null,
--isCorrect bit default 0 -- multiple correct answers
foreign key(questionId) references dbo.questions(id)
)
go
alter table dbo.questions
add constraint fk_questions_answers foreign key (correctAnswerId) references dbo.answers(id)

//.aspx page
<!DOCTYPE html>
<%@ Page Language="C#" %>
<script runat="server">

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        int questions = 0;
        int correct = 0;
        //int questionId // if you want to save it
        //int answerId // if you want to save it
        foreach(RepeaterItem item in rpQuestions.Items)
        {
            if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
            {
                questions++;
                string correctAnswerId = ((Literal)item.FindControl("correctAnswerId")).Text;
                var answerList = item.FindControl("lstAnswers") as RadioButtonList;
                if (answerList.SelectedValue == correctAnswerId)
                    correct++;
            }
        }
        result.Text = string.Format("{0} correct answers out of {1}", correct, questions);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>quiz ver 0.0</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Repeater ID="rpQuestions" runat="server" DataSourceID="sqlQuestions">
                <ItemTemplate>
                    <asp:Literal ID="questionId" runat="server" Text='<%#Eval("id") %>' Visible="false"></asp:Literal>
                    <asp:Literal ID="correctAnswerId" runat="server" Text='<%#Eval("correctAnswerId") %>' Visible="false"></asp:Literal>
                    <h2><asp:Literal runat="server" Text='<%#Eval("question") %>'></asp:Literal></h2>
                    <%-- radio buttons are easier to use than dropdown --%>
                    <asp:RadioButtonList ID="lstAnswers" runat="server" DataTextField="answer" DataValueField="id" DataSourceID="sqlAnswers"></asp:RadioButtonList>
                    <%-- Bind possible answers declarativelly --%>

                    <%-- This DataSource must be inside ItemTemplate --%>
                    <asp:SqlDataSource ID="sqlAnswers" runat="server" ConnectionString="<%$ ConnectionStrings:DBConnection %>"
                        SelectCommand="SELECT id, answer FROM dbo.answers where questionId=@questionId">
                        <SelectParameters>
                            <asp:ControlParameter Name="questionId" ControlID="questionId" PropertyName="Text" Type="Int32" />
                        </SelectParameters>
                    </asp:SqlDataSource>
                </ItemTemplate>
            </asp:Repeater>
            <asp:SqlDataSource ID="sqlQuestions" runat="server" ConnectionString="<%$ ConnectionStrings:DBConnection %>" 
                SelectCommand="SELECT id, question, correctAnswerId FROM questions"></asp:SqlDataSource>
            <asp:Button ID="btnSubmit" runat="server" Text="Submit answers" OnClick="btnSubmit_Click" />
            <div>
                <asp:Literal ID="result" runat="server"></asp:Literal>
            </div>
        </div>
    </form>
</body>
</html>

您已經知道要設置的屬性,不需要反射:

Dim objAnswers As New DAL.Quiz.QuizAnswers
Dim answers = New Dictionary(Of String, String)
Dim i as Integer
For i = 0 To repeater1.Items.Length - 1
    Dim ddlAnswers = CType(repeater1.Items(i).
         FindControl("DropDownList1"), App_Controls_Forms_DropDownList)        
    answers.Add("Question" & i + 1,  ddlAnswers.SelectedText)
Next

objAnswers.Question1=answers(NameOf(objAnswers.Question1))
objAnswers.Question2=answers(NameOf(objAnswers.Question2))
objAnswers.Question3=answers(NameOf(objAnswers.Question3))
objAnswers.Question4=answers(NameOf(objAnswers.Question4))
objAnswers.Question5=answers(NameOf(objAnswers.Question5))

更好的是擁有一個接受字典的構造函數,並從那里設置屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM