丢失组件选择GridView后的SelectIndexChanged

时间:2013-01-25 05:09:15

标签: c# asp.net user-controls code-behind webusercontrol

当我在UserControl的GridView中选择行时。这个gridview消失了。

主页(aspx页面)

1.1.Html

<body>
    <form id="form1" runat="server">
    <div>
    <asp:PlaceHolder ID="plh" runat="server"></asp:PlaceHolder>
    </div>
    </form>
</body>

1.2.CodeBehind

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Test2.Admin.WebUserControl1[] wuc = new Test2.Admin.WebUserControl1[2];
            for (int i = 0; i < 2; i++)
            {
                plh.Controls.Add(new LiteralControl("<div id='dvChannel' runat='server' style='width: 200px;float:left;padding-left:20px;'>"));
                wuc[i] = (Test2.Admin.WebUserControl1)LoadControl("WebUserControl1.ascx");
                wuc[i].ID = "wuc" + i.ToString();
                plh.Controls.Add(wuc[i]);
                plh.Controls.Add(new LiteralControl("</div>"));
            }
        }
    }

用户控件

2.1.html

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="Test2.Admin.WebUserControl1" %>
<asp:GridView ID="GridView1" runat="server" AutoGenerateSelectButton="true"
OnSelectedIndexChanged="gvSelected">
</asp:GridView>

2.2.Codebehind

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                var list = (new[] { 
                new { Price = 30 } ,
                new { Price = 30 },
                new { Price = 30 },
                new { Price = 30 }
                });
                GridView1.DataSource = list;
                GridView1.DataBind();
            }
        }
        protected void gvSelected(object sender,EventArgs e)
        {
            GridViewRow row = GridView1.Rows[GridView1.SelectedIndex];
            row.BackColor = Color.Red;//Set red color for this row on gridview
        }

当我在UserControl的GridView上选择行时,这个gridview消失了。 我该怎么做才能让它正常工作。 你有任何解决方案吗?

1 个答案:

答案 0 :(得分:0)

即使在回发中也需要加载GridView。 尝试删除条件 - if(!Page.IsPostBack)

或者,在else块中写一个不同的代码片段 - 用于设置数据源&amp;绑定网格。