Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » ASP.NET Controls » Using a Web User Control inside the GridView control

Using a Web User Control inside the GridView control

In this article I will share how a Web User Control can be used in the GridView control. The examples are written using C# .

Author Rank :
Page Views : 42418
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Developing some web site we often should use some control in the GridView control. In this case we have to create the GridView control with TemplateField columns and use some special methods to access needed data. Inside the GridView control we can use both standard server controls (such as DropDownList , etc.) and our own controls. In this article I will show how a web user control can be used in the GridView control. As example we will use our old friend : the ListBoxesFT_C control.

We will use our WebSites_Test solution . To the WF_ListBoxes.aspx we will add the GridView control.

Our GridView control, named just "GridView1", has caption "TestUC_InsideGV" and consists of five columns.

The first  one is "the type of" the BoundField and contains some "Identity number"; the HeaderText property of this column is "Num".

The second column is the TemplateField and contains our ListBoxesFT_C control with Id = "ListBoxesFT_C2"; the HeaderText property of this column is "UC". 

The third column is the  ComandField (the select column) and allows to check out the "out data" of the selected row of the GridView1 control; the HeaderText property of this column is "Select".

The fourth column is the TemplateField and contains GridView control with Id = "GridView_Inside", which allows to display the C_DataOut property of the ListBoxesFT_C2 for selected row; the HeaderText property of this column is "Test_GridView".

The fifth column is the TemplateField and contains two TextBox controls with Id="TextBox_Text" and Id="TextBox_Value",  which allow to display the C_DataOut property as text and value; the HeaderText property of this column is "Test_TextValue".

We also will use our GridViewTestDT_Out (with the caption "TestSelect_All") to display all selected value and text according to "Num" column; we will do that with the help of the ButtonTestDTOut button click.

For our task we don't need the ListBoxesFT_C1 control and we just change the Visible property to "false".

The design of the WF_ListBoxes.aspx is looked now like this ( fig. 1).

 

Figure 1.

The source code for GridView1 is following: 

<asp:GridView ID="GridView1" runat="server"

        AutoGenerateColumns="False"

        OnSelectedIndexChanged="GridView1_SelectedIndexChanged"

        Caption="TestUC_InsideGV">

    <Columns>

        <asp:BoundField DataField="Num" HeaderText="Num" />

        <asp:TemplateField HeaderText="UC">

            <ItemTemplate >

                <uc1:ListBoxesFT_C ID="ListBoxesFT_C2" 

                    runat="server" C_HeightLB ="70" C_WidthLB ="80"

                    C_Client= "false"

                    C_DataIn ='<%# getDT_ForTemplate()%>'/>

            </ItemTemplate>

        </asp:TemplateField>

        <asp:CommandField ShowSelectButton="True" HeaderText="Select"/>

        <asp:TemplateField HeaderText="Test_GridView">

            <ItemTemplate >

                <asp:GridView ID="GridView_Inside" runat="server" >

                </asp:GridView>

            </ItemTemplate>

        </asp:TemplateField>

        <asp:TemplateField HeaderText="Test_TextValue">

            <ItemTemplate >

                <asp:TextBox ID="TextBox_Text" runat="server" >

                </asp:TextBox>

                <asp:TextBox ID="TextBox_Value" runat="server" >

                </asp:TextBox>

            </ItemTemplate>

        </asp:TemplateField>

    </Columns>

</asp:GridView> 

As you can see we set the property C_DataIn of the ListBoxesFT_C2 control to some value with  the help of the getDT_ForTemplate() method.

Now we have to add some code to the WebForms_Test_WF_ListBoxes partial class.

First of all add protected method getDT_ForTemplate where we use one of our old friends GetData.GetDataHelp (of course, you can use your own source to get  and return a DataTable ): 

protected DataTable getDT_ForTemplate()

{

    GetData.GetDataHelp getData = new GetData.GetDataHelp();

    return (getData.getDataSetCities(4).Tables[0]);
}
 

In order to fill column "Num" add to the protected void Page_Load method the following code: 

GetData.GetDataHelp getData_GV = new GetData.GetDataHelp();

if (!IsPostBack)

{

    GridView1.DataSource = getData_GV.getDataSetNum(3).Tables[0];

    GridView1.DataBind();
}

Here I use the method (getDataSetNum), that just returns numbers as DataSet (again, you can use your own source):  

//The method getDataSetNum that returns dataSet with

//one dataTable "DataTableNum". The dataTable consists of

//one column :  "Num" .

//The dataTable is filled with the help of

//the "for" loop; the number of the rows is input parameter.

//

public DataSet getDataSetNum(int iRows)

{

    DataTable dt = new DataTable("DataTableNum");

    DataColumn dc_Num;

    DataRow dRow;

    DataSet ds = new DataSet();

 

    ds.Clear();

    dc_Num = new DataColumn("Num", Type.GetType("System.String"));

    dt.Columns.Add(dc_Num);

    for (int i = 0; i < iRows; i++)

    {

        dRow = dt.NewRow();

        dRow["Num"] = i.ToString() ;

        dt.Rows.Add(dRow);

    }

    ds.Tables.Add(dt);

    return ds;
}
 

Now we add code to the method GridView1_SelectedIndexChanged , which is "responsible" for the SelectedIndexChanged event, that is fired when we click on the select column. First of all we have to create DataTable dt, that in fact is the C_DataOut property of the ListBoxesFT_C2 control of the selected row: 

DataTable dt = ((UserControls_ListBoxesFT_C)GridView1;
    SelectedRow.FindControl("ListBoxesFT_C2")).C_DataOut;
 

Secondly we find for the selected row the GridView_Inside control: 

GridView gv = ((GridView)GridView1;
    SelectedRow.FindControl("GridView_Inside"));

Then we just bind gv : 

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

Now in our hands there are DataTable dt, and we can, with the help of  the loop, to fill out the TextBox_Text and TextBox_Value controls of the selected row: 

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)

{

    DataTable dt = ((UserControls_ListBoxesFT_C)GridView1.

        SelectedRow.FindControl("ListBoxesFT_C2")).C_DataOut;

    GridView gv = ((GridView)GridView1.

        SelectedRow.FindControl("GridView_Inside"));

 

    gv.DataSource = dt;

    gv.DataBind();

    string sText = "";

    string sValue = "";

    int iRows ;

    int iCount ;

    iRows = dt.Rows.Count;

    for (iCount = 0; iCount < iRows; iCount++)

    {

        sText += dt.Rows[iCount][1].ToString();

        if (iCount != iRows - 1)

        {

            sText += ";";

        }

        ((TextBox)GridView1.SelectedRow.

            FindControl("TextBox_Text")).Text = sText;

        sValue += dt.Rows[iCount][0].ToString();

        if (iCount != iRows - 1)

        {

            sValue += ";";

        }

        ((TextBox)GridView1.SelectedRow.

            FindControl("TextBox_Value")).Text = sValue;
    }
}
 

OK! Now let's create the method getDataSetGV. This method returns DataSet with one table "DataTableGV", that consists of two columns : "Num" and "Text". We have to loop through the GridView1 control and "to write down" in the "Num" column all value of the "Num" column of the GridView1 control and in the "Text" column all selected value (text) according to the "Num" column. Again we use FindControl method: 

private DataSet getDataSetGV()

{

    GridViewRow grRow ;  

    DataTable dt = new DataTable("DataTableGV");

    DataColumn dc_Num;

    DataColumn dc_Text;

    DataRow dRow;

    DataSet ds = new DataSet();

    int iRowsGV;

 

    ds.Clear();

    dc_Num = new DataColumn("Num", Type.GetType("System.String"));

    dt.Columns.Add(dc_Num);

    dc_Text = new DataColumn("Text", Type.GetType("System.String"));

    dt.Columns.Add(dc_Text);

 

    iRowsGV = GridView1.Rows.Count;

    for (int i=0; i < iRowsGV; i++)

    {

        grRow = GridView1.Rows[i];

        dRow = dt.NewRow();

        dRow["Num"] = grRow.Cells[0].Text;

        DataTable dtInside = ((UserControls_ListBoxesFT_C)GridView1.

            Rows[i].FindControl("ListBoxesFT_C2")).C_DataOut;

        string sTextInside = "";

        int iRowsInside;

        int iCountInside;

        iRowsInside = dtInside.Rows.Count;

        for (iCountInside = 0; iCountInside < iRowsInside; iCountInside++)

        {

            sTextInside += dtInside.Rows[iCountInside][1].ToString();

            if (iCountInside != iRowsInside - 1)

            {

                sTextInside += ";";

            }

        }

        dRow["Text"] = sTextInside;

        dt.Rows.Add(dRow);

    }

    ds.Tables.Add(dt);

    return ds;
}
 

We use this method to set the DataSource property of the GridViewTestDT_Out control when we click on the button ButtonTestDTOut: 

protected void ButtonTestDTOut_Click(object sender, EventArgs e)

{

    GridViewTestDT_Out.DataSource = getDataSetGV().Tables[0] ;

    GridViewTestDT_Out.DataBind();
}
 

Now we can test how our control works inside the GridView control. Choose some values in every control (column "UC") :

Figure 2. 

click on select column and you will see the result like this (fig. 3).

Figure 3. 

If you click on the the button ButtonTestDTOut ("Test DT_Out") you will get all selected values in one table "TestSelect_All" (fig. 4).

Figure 4.

CONCLUSION 

I hope that this article will help you to create the GridView control with a user control (your own web user controls or just standard server controls) and receive all needed data from the built in control.

Good luck in programming ! 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Michael Livshitz
Michael is a lead programmer for a large technological firm. He has experience working with .NET projects (ASP.NET and Windows) since 2002. Currently used languages are C#, VB.NET, T-SQL and JavaScript. He also has experience working with C, Visual Basic, Oracle, SQL Server, and Access.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
query by Abdul On April 2, 2007
you had written that "We will use our WebSites_Test solution . To the WF_ListBoxes.aspx we will add the GridView control." this does not clarify that you are taking this from previos examples or you are starting with fresh one and you had not given the database details so please do the same that will help to understand this clearly Thank You
Reply | Email | Modify 
Its Urgent by ram On March 10, 2008
can u please show the full code including dll files
Reply | Email | Modify 
Re: Its Urgent by Michael On March 17, 2008

Hi!

Please, see my articles (for full code):

1.

http://www.c-sharpcorner.com/UploadFile/LivMic/WebControl_ListBoxesFT_111052006102331AM/WebControl_ListBoxesFT_1.aspx

2.

http://www.c-sharpcorner.com/UploadFile/LivMic/WebControl_ListBoxesFT_211082006003338AM/WebControl_ListBoxesFT_2.aspx

3.

http://www.c-sharpcorner.com/UploadFile/LivMic/WebControl_ListBoxesFT_311092006153114PM/WebControl_ListBoxesFT_3.aspx

4.

http://www.c-sharpcorner.com/UploadFile/LivMic/WebControl_ListBoxesFT_411102006145254PM/WebControl_ListBoxesFT_4.aspx

5.

http://www.c-sharpcorner.com/UploadFile/LivMic/WebControl_ListBoxesFT_511112006135900PM/WebControl_ListBoxesFT_5.aspx

Good luck!

Michael

 

 

Reply | Email | Modify 
good by zeng On August 26, 2008
Althrough it's so obvious, I can't understand that all. beecause the level of English is not proficiency.
Reply | Email | Modify 
good by zeng On August 26, 2008
Althrough it's so obvious, I can't understand that all. beecause the level of English is not proficiency.
Reply | Email | Modify 
good by zeng On August 26, 2008
Althrough it's so obvious, I can't understand that all. beecause the level of English is not proficiency.
Reply | Email | Modify 
code to Download by s On October 20, 2009
can you provide the project download link
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.