Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET & Web Forms » 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:
Technologies: ASP.NET 1.0, Controls,Visual C# .NET
Total downloads :
Total page views :  26375
Rating :
 5/5
This article has been rated :  1 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
Become a Sponsor



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 ! 


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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Powerful ASP.NET Hosting w/ NO Setup Fees. Click Here!
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 | Delete | Modify | 
Its Urgent by ram On March 10, 2008
can u please show the full code including dll files
Reply | Email | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | Modify | 
code to Download by s On October 20, 2009
can you provide the project download link
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved