更改datalist中按钮上的文本不起作用

时间:2013-12-17 03:34:45

标签: c# asp.net

我有以下代码,它可以更改URL,但不会更改按钮上的文本。我错过了什么?该按钮位于数据列表中,我想在按下时更改按钮上的文本。应该发生的是用户点击测验按钮,URL应该更改为quizURL(这是有效的)。同时按钮上的文本应更改为视频(这不起作用)。然后,当用户点击相同的按钮时,它将切换回测验。我正试图用一个按钮作为切换来显示测验或视频。

<asp:Button ID="btnQuizVid" runat="server" Text="Quiz" CommandName="quiz" CssClass="buttonStyleGrey" />


protected void trainingDataList_ItemCommand(object source, DataListCommandEventArgs e)
{
    List<Material> dataset = null;
    string btnText = ((Button)(trainingDataList.Items[e.Item.ItemIndex].FindControl("btnQuizVid"))).Text;

    if (e.CommandName == "quiz")
    {
        dataset = BasicCRUDtoolkit.GetMaterialByProfFocus(hdnTypeSelect.Value);
        Button tmpBtn = e.Item.FindControl("btnQuizVid") as Button;

        if (btnText == "Quiz")
        {
            tmpBtn.Text = "Video";
            tmpBtn.DataBind();
            dataset[e.Item.ItemIndex].videoURL = dataset[e.Item.ItemIndex].quizURL;

        }
        else
        {
            tmpBtn.Text = "Quiz";
            dataset[e.Item.ItemIndex].videoURL = dataset[e.Item.ItemIndex].videoURL;

        }

        trainingDataList.DataSource = dataset;
        trainingDataList.DataBind();
    }

}

2 个答案:

答案 0 :(得分:0)

您在按钮标记中缺少OnCommand值,因此您在标记中设置的CommandName值不知道触发时要调用的内容。将OnCommand值添加到按钮标记中,如下所示:

<asp:Button ID="btnQuizVid" runat="server" Text="Quiz" CommandName="quiz" 
            CssClass="buttonStyleGrey" 
            OnCommand="trainingDataList_ItemCommand" />

获取按钮控件一次,不要在按钮上调用.DataBind(),因为只需更改Text属性即可反映更改,因为代码在将HTML发送到浏览器之前执行。将您的代码更改为:

protected void trainingDataList_ItemCommand(object source, 
                                            DataListCommandEventArgs e)
{
    List<Material> dataset = null;
    var theButton = trainingDataList.Items[e.Item.ItemIndex]
                                    .FindControl("btnQuizVid") as Button;

    if (e.CommandName == "quiz")
    {
        dataset = BasicCRUDtoolkit.GetMaterialByProfFocus(hdnTypeSelect.Value);

        if (theButton.Text == "Quiz")
        {
            theButton.Text = "Video";
            dataset[e.Item.ItemIndex].videoURL = dataset[e.Item.ItemIndex].quizURL;
        }
        else
        {
            theButton.Text = "Quiz";
            dataset[e.Item.ItemIndex].videoURL = dataset[e.Item.ItemIndex].videoURL;
        }

        trainingDataList.DataSource = dataset;
        trainingDataList.DataBind();
    }
}

答案 1 :(得分:0)

我想您需要在Button tmpBtn = e.Item.FindControl("btnQuizVid") as Button;后执行theButton.Text = "Video";DataBind();