[英]How can I call a server side method from a linkbutton inside a gridview I am building programatically?
我有以下代碼。 我以編程方式構建了一個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;
}
}
}
}
您需要為鏈接按鈕添加一個處理程序,以在Click事件上調用lb_Click。
lb.Click += lb_Click;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.