如何从gridview中的链接按钮调用服务器端方法我正在以编程方式构建?

时间:2009-06-22 23:54:43

标签: c# gridview server-side linkbutton

我有以下代码。 我以编程方式构建了一个grdiview,然后我将其中一个列更改为linkbuttons。不幸的是,它从不回调服务器端lb_Click方法。 有没有人面对这个?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (CommonMethods.logOn(Request.ServerVariables["LOGON_USER"]))
        {
            Response.Redirect("http://www.google.com");
        }

        // Now we have to build the questions
        using (var context = new nVoteDataContext())
        {
            var retrievedQuestions = from q in context.questions
                                     select new
                                                {
                                                    q.id,
                                                    q.question1,
                                                    q.questionType
                                                };

            GridView_questions.DataSource = retrievedQuestions;
            GridView_questions.DataBind();
            GridView_questions.HeaderRow.Cells[0].Text = "#";
            GridView_questions.HeaderRow.Cells[1].Text = "Question";

            foreach (GridViewRow s in GridView_questions.Rows)
            {
                if (s.RowType == DataControlRowType.DataRow)
                {
                    var lb = new LinkButton();
                    lb.CausesValidation = true;
                    lb.Attributes.Add("runat", "server");
                    lb.CommandName = "lb_Click";
                    lb.CommandArgument = s.Cells[0].Text;
                    lb.Text = s.Cells[1].Text;
                    s.Cells[1].Text = string.Empty;
                    s.Cells[1].Controls.Add(lb);
                }
            }

        }
    }

    public void lb_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow s in GridView_questions.Rows)
        {
            if (s.RowType == DataControlRowType.DataRow)
            {
                s.BackColor = System.Drawing.Color.Red;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您需要为linkbutton添加一个处理程序,以便在Click事件

上调用lb_Click
lb.Click += lb_Click;