开发者

Adding WebUserControl To Gridview in asp.net

I want to add a webusercontol which contains a textbox 开发者_高级运维and a label to the gridview control. I am binding a gridview with a datatable dynamically.

Here is my code:

@ Register Src="CompareBox.ascx" TagName="CompareBox" TagPrefix="objCompareBox" %><br>
<asp:GridView ID="grdfoneBoxContainer" runat="server">
         <Columns><br>
              <asp:TemplateField HeaderText="User control"> <br>
                  <ItemTemplate><br>
                      <objCompareBox:CompareBox ID="CompareBoxCol1" runat="server"/><br>
                  </ItemTemplate><br>
              </asp:TemplateField><br>
         </Columns><br>
</asp:GridView><br>

    DataTable dt = new DataTable();
    dt.Columns.Add("uc1");
    dt.Columns.Add("uc2");
    dt.Columns.Add("uc3");
    dt.Columns.Add("uc4");

    CompareBox objCompareBox = new CompareBox();
    objCompareBox.txt= "World";
    objCompareBox.lbl = "Hello";

    dt.Rows.Add(objCompareBox, objCompareBox, objCompareBox, objCompareBox);
    dt.Rows.Add(objCompareBox, objCompareBox, objCompareBox, objCompareBox);
    dt.Rows.Add(objCompareBox, objCompareBox, objCompareBox, objCompareBox);
    dt.Rows.Add(objCompareBox, objCompareBox, objCompareBox, objCompareBox);


    grdfoneBoxContainer.DataSource = dt;
    grdfoneBoxContainer.DataBind();

txt & lbl are two properties that are declared in WebUserControl but it's giving object reference error .

Thanks,


you have to intercept that object within the RowDataBound event.

After you have call grdfoneBoxContainer.DataBind(); if you write and handler for the event RowDataBound:

protected void grdfoneBoxContainer_RowDataBound(object sender, GridViewRowEventArgs e) { if(e.Row.RowType==DataControlRowType.DataRow) { CompareBox compareBox = (CompareBox) e.Row.FindControl("CompareBoxCol1");

        //here you have a reference to your control
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜