How to add a Web server or HTML server controls (such as CheckBox) to the template in GridView and bind the controls to a data source.

How to add a Web server or HTML server controls (such as CheckBox) to the template in GridView and bind the controls to a data source.

Normally, We can add a Web server or HTML server controls to the template in GridView control,just like the Code 1
I hope to do the same thing by programming (just like the Code 2), but I can ony add the BoundField,
I don't know how to add a CheckBox control to the template in GridView , could you help me?


//--------------------------------------------Code 1------------------------------------------------------------
<asp:GridView AutoGenerateColumns="False" DataKeyNames="CustomerID" DataSourceID="SqlDataSource1" ID="GridView1" runat="server">
    <Columns>
        <asp:TemplateField>
           <ItemTemplate>
             <input id="CustomerID" type="checkbox" runat="server" value='<%# Eval("CustomerID") %>' />
           </ItemTemplate>
       </asp:TemplateField>

       <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName"/>
       <asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName"/>
    </Columns>
</asp:GridView>
//--------------------------------------------Code 1------------------------------------------------------------

 

//--------------------------------------------Code 2------------------------------------------------------------
            myParGetBookmarks.myGridView.Columns.Clear();
          
            BoundField a1 = new BoundField();
            a1.DataField = "Id";
            a1.HeaderText = "Id";
            a1.SortExpression = "Id";
            a1.Visible = false;

            BoundField a2 = new BoundField();
            a2.DataField = "Title";
            a2.HeaderText = "Title";
            a2.SortExpression = "Title";

            myParGetBookmarks.myGridView.Columns.Add(a1);
            myParGetBookmarks.myGridView.Columns.Add(a2);

//--------------------------------------------Code 2------------------------------------------------------------


SuperCool Multiple ZIP - A utility to unzip multiple files and work with multiple zip files

SuperCool Random Number Generator
0
mycwcgr
10/16/2005 2:33:56 AM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

2 Replies
1308 Views

Similar Articles

[PageSpeed] 43

You can create and add controls in the RowCreated Event. I have copied an example from the VS 2005 Help files and modified it slightly. You will need to figure out how to persist state through roundtrips, as these controls are recreated on every PostBack. A better solution would perhaps be to hide/show Controls/Columns depending on scenario.

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)

{

// If multiple buttons are used in a GridView control, use the

// CommandName property to determine which button was clicked.

if (e.CommandName == "Add")

{

// Convert the row index stored in the CommandArgument

// property to an Integer.

int index = Convert.ToInt32(e.CommandArgument);

// Retrieve the row that contains the button clicked

// by the user from the Rows collection.

GridViewRow row = CustomersGridView.Rows[index];

// Create a new ListItem object for the customer in the row.

ListItem item = new ListItem();

item.Text = Server.HtmlDecode(row.Cells[2].Text);

// Find, enable and check the Added Checkbox

CheckBox chk = (CheckBox)row.Cells[4].Controls[0];

chk.Enabled = true;

chk.Checked = true;

// If the customer is not already in the ListBox, add the ListItem

// object to the Items collection of the ListBox control.

if (!CustomersListBox.Items.Contains(item))

{

CustomersListBox.Items.Add(item);

}

}

}

void CustomersGridView_RowCreated(Object sender, GridViewRowEventArgs e)

{

// The GridViewCommandEventArgs class does not contain a

// property that indicates which row's command button was

// clicked. To identify which row's button was clicked, use

// the button's CommandArgument property by setting it to the

// row's index.

if (e.Row.RowType == DataControlRowType.DataRow)

{

// Instantiate a new CheckBox

CheckBox chk = new CheckBox();

chk.Enabled = false;

// Add it to the Control Collection

e.Row.Cells[4].Controls.Add(chk);

 

 

// Retrieve the LinkButton control from the first column.

LinkButton addButton = (LinkButton)e.Row.Cells[0].Controls[0];

// Set the LinkButton's CommandArgument property with the

// row's index.

addButton.CommandArgument = e.Row.RowIndex.ToString();

}

}

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<h3>

GridView RowCommand Example</h3>

<table width="100%">

<tr>

<td width="50%">

<asp:GridView ID="CustomersGridView" runat="server" AllowPaging="True" AutoGenerateColumns="False"

DataSourceID="CustomersSource" OnRowCommand="CustomersGridView_RowCommand" OnRowCreated="CustomersGridView_RowCreated"

BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px"

CellPadding="4" ForeColor="Black" GridLines="Vertical">

<Columns>

<asp:ButtonField CommandName="Add" Text="Add" />

<asp:BoundField DataField="CustomerID" HeaderText="Customer ID" />

<asp:BoundField DataField="CompanyName" HeaderText="Company Name" />

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

<asp:TemplateField HeaderText="Add Column"></asp:TemplateField>

</Columns>

<FooterStyle BackColor="#CCCC99" />

<RowStyle BackColor="#F7F7DE" />

<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />

<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />

<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />

<AlternatingRowStyle BackColor="White" />

</asp:GridView>

</td>

<td valign="top" width="50%">

Customers:

<br />

<asp:ListBox ID="CustomersListBox" runat="server"></asp:ListBox>

</td>

</tr>

</table>

<!-- This example uses Microsoft SQL Server and connects -->

<!-- to the Northwind sample database. Use an ASP.NET -->

<!-- expression to retrieve the connection string value -->

<!-- from the Web.config file. -->

<asp:SqlDataSource ID="CustomersSource" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString1 %>"

SelectCommand="Select [CustomerID], [CompanyName], [City] From [Customers]" ProviderName="<%$ ConnectionStrings:NorthwindConnectionString1.ProviderName %>">

</asp:SqlDataSource>

</div>

</form>

</body>

</html>


Regards

Andre Colbiornsen
---------------------------------
Seventh Day
Råbygatan 1A,
SE-223 61 Lund
Sweden
Mob.: +46-(0)708-97 78 79
Mail: info@seventhday.se
--------------------------------
0
adec
10/16/2005 4:23:41 AM
You cannot add a late binding exression inside a server control which gets parsed early in the cycle, even if it is not really a server control, but just an html snippet. It is still inside the template.

However you could do it in code in the databinding event handler.

HTH


Regards,

Rob
0
rmprimo
10/16/2005 4:25:36 AM
Reply:

Similar Artilces:

html server controls and web server controls
hello what is the difference between html server controls and web server controls? what is the main goal of converting html elements to html server controls , so why i can directly use the web server controls instead of converting process? thank you for the help and for the time If you convert a normal html control to a html server control then you can work with and reference it programmatically. MS advises using web controls where possible. But if your application uses vast amounts of html controls its far easier to just apply runat="server" than to re invent them a...

HTML Server Control or Web Server Control?
Hi, Being new to ASP.NET I have one thing confusing me much. 1. Whats the major difference between HTML Server Control and Web Server Control? 2. Whats the advantage of processing all the HTML Controls in Server? Server will not be overloaded with this? Which one should I use?..Plain HTML or HTML Server Control or Web Server Control? Thanks and Regards _________________ ASP 2 ASP.NET FYI: http://msdn.microsoft.com/msdnmag/issues/01/09/asp/toc.asp Colt Hi Colt, Thanks for the link. I personally prefer server controls - - there are so many more possi...

Difference between Web Server control and HTML Server control
 HI, I want to know what is the main difference between html server control and web server controls.Thanks in advanceVikram Vikram www.vikramlakhotia.comPlease mark the answer if it helped you  The difference is that html server controls have syntax and rendering closely mapped to html objects.  Where as web server controls have more relation to the .NET Framework. Web server controls have a richer and wider range of special purpose controls.  Calenders, tree views, etc.. If a post helps you please mark it as an answer.  Is that the only difference...

HTML Server Controls V/s. Web Server Controls?
How does one understand when to use HTML Server Controls & when to use Web Server Controls in a Web Form? In other words, when should HTML Server Controls be used & when should Web Server Controls be used in a Web Form?ThanksRON*********If you have an apple & I have an apple & we exchange our apples, then each of us will still have only 1 apple but if you have an idea & I have an idea & we exchange our ideas, then each of us will have 2 ideas Web Server Controls should always be used. HTML Server controls were meant so that a standard HTML page could ...

Web Server Control Containing another Web Server Control?
I'm building a web server control that needs to include functionality from 3rd party web server control, ASPNetMenu. My web server control needs to render ASPNetMenu at runtime to create a menu. I'd like to do this so that my control's parent ASPX page does not need to register ASPNetMenu or make any configuration changes as this should be done through my web server control. Does anybody have any suggestions on how to do this? Mike - Cache entire web sites at the client and server and keep cache current. Cache just got easier! There are two articles that you would want to be int...

how to add a server control to a page from other server control
I have a control that needs to be added at a precise location on a web form using a server control i designed. I tried to add the control using this.Controls.add(controlName) but its just appending to the existing control. Is there a way to add a control to another control at a precise location?  I think adding it to a string builder is a feasible option for me, but I guess I cant do that. any suggestions as to how to implement it please? in one control you add PlaceHolder, And Create one Public property which return PlaceHolder..  then when you add the control in Web For...

HTML Controls or Web Server Controls?
there are  2 different categories of controls in asp.net2.0, the HTML controls and WebServer controls, what are the differences in terms of usage? or in what circumstances each of these 2 categories should be used?Achievement provides the only real pleasure in life The HTML controls are primarily used when porting old ASP applications (or plain HTML) pages to ASP.NET. They are also sometimes used when you want to write large amounts of client-side JavaScript. The ASP.NET server-side controls are used when you want to write server-side code to get/set the values of the controls (but ...

HTML server control and web controls
I would like to know when to use HTML controls with runat=server and web controls? and what is the difference between these two thanksfeed the creative machine The biggeest difference is that you can access a control's properties in the code-behind if it contains 'runat=server'...If you have a label control that you will not need to change in any way, use the HTML control - if you will be changing the text of the label, you can add 'runat=server' to the HTML control or use the label server control... Just remember - to change the text of a label server control, you would co...

how to have both server controls and html controls rendered in a custom control?
I have a custom control in which there is an html text box.when you click on it , a div containing a table is appeared and according to what you select in that table a text is set to the text box. It works fine but the problem is: as the text box is an html element it doesn't have viewstate and when a post back occures in the page its value disappeares.I tried a hidden field to keep its value.again there is another problem : I put this custom control in a usercontrol and put the usercontrol in a multiview and by clicking on a button this view is selected and by clicking another bu...

How to 'programmatically' add controls to the template of a Templated Server Control ?
Hi all,I am trying to build a Templated Server Control based on an example in MSDN here.  Everything worked ok.Now, as the next step, I would like to do the followings:1. Add new controls to the template programmatically. For example, adding a TextBox and a Button2. Persist these newly added controls 'and' their value between postback.  So, if users fill-in the above TextBox and click on the Button, I would like to persist the value that the user filled into the TextBox.3. Wire these controls' events. For example, I want to wire the OnClick event of the above Button.4. Have referen...

Add controls to a server control
Hi,I have something like this<MyControls:SomeControl Id... runat...>    <MyControls:OtherControl Id... runat.../>    <MyControls:OtherControl Id... runat.../>    <MyControls:OtherControl Id... runat.../>...</MyControls:SomeControl Id... runat...>My class SomeControl has a MyOtherControlList ( as List<OtherControlType>) and a propertypublic OtherControlType OtherControl {    set { MyOtherControlList.Add(value); }}I never get into the property set() method. What am I doing wrong? What do I need to d...

html control, server control
what is the difference between html control, server control and web controls See this post - http://forums.asp.net/thread/1553414.aspx Though if using a templated control I would not use either unless I need the value of the control on postback. Simple use literals with bound attributes. Rgds, Martin.Rgds,Martin.For the benefit of all users please mark any post answers as appropriate. "A square is a rectangle, but a rectangle is not a square."   A 'Control' is the basis for all ASP controls.  It has certain properties and methods that other, more developed controls c...

Server Controls or Html controls ?
In performace wise what should i prefer Html control or Server Controls ?News & Reviews | Matrimonial | Mithila an HTML control should be slightly lighter than a server control. For example Img is slightly lighter than ASP:Image To be honest though, the difference is negligable and i generally use whichever control best meets my needs with specifically considering any performance difference between them.  Mike Banavige~~~~~~~~~~~~Need a site code sample in a different language? Try converting it with: http://converter.telerik.com/...

Server Control inside Server Control
I'm developing a server control that in turns contains another server control (i.e. Label). I instantiate the label and expose the entire Label through a property.   Imports System Imports System.Web Imports System.Web.UI Public Class Class1     Inherits Control       Dim _label As New WebControls.Label     Public Property L() As WebControls.Label         Get             Return _label         End Get ...

Web resources about - How to add a Web server or HTML server controls (such as CheckBox) to the template in GridView and bind the controls to a data source. - asp.net.presentation-controls

Resources last updated: 11/24/2015 11:00:09 PM