473,769 Members | 6,267 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

GridView generated programmaticall y

<asp:GridView ID="Basic" runat="server"
DataKeyNames="Q uestionID,isHea ding" AutoGenerateCol umns="false"
AllowPaging="tr ue" PageSize="100">
<Columns>
<asp:BoundFie ld Visible="false" DataField="Ques tionID"
HeaderText="Que stionID"></asp:BoundField>
<asp:BoundFie ld DataField="Ques tionDesc"
HeaderText="Que stion"
ItemStyle-HorizontalAlign ="Left"></
asp:BoundField>
<asp:TemplateFi eld HeaderText="Ans wer">
<ItemTemplate >
<asp:RadioButto nList
RepeatDirection ="Horizontal " runat="server"
ID="rdAnswer" SelectedIndex=' <%#
SetState(DataBi nder.Eval
(Container.Data Item,"Answer")) %>'>
<asp:ListItem Value="0">Yes</
asp:ListItem>
<asp:ListItem Value="1">No</
asp:ListItem>
</asp:RadioButton List>
</ItemTemplate>
</asp:TemplateFie ld>
</Columns>
</asp:GridView>

Hello,

I need to create a gridview programmaticall y in code that would be
similar to the above code (in design mode).\

Any pointers?

Thanks,

Mar 28 '07 #1
5 23633
Someones already done it for you.
http://forums.asp.net/thread/1379019.aspx

Not sure why you wouldn't just use a templated gridview though!

Regards

John Timney (MVP)
http://www.johntimney.com
http://www.johntimney.com/blog
"NKaufman" <na****@hotmail .comwrote in message
news:11******** *************@o 5g2000hsb.googl egroups.com...
<asp:GridView ID="Basic" runat="server"
DataKeyNames="Q uestionID,isHea ding" AutoGenerateCol umns="false"
AllowPaging="tr ue" PageSize="100">
<Columns>
<asp:BoundFie ld Visible="false" DataField="Ques tionID"
HeaderText="Que stionID"></asp:BoundField>
<asp:BoundFie ld DataField="Ques tionDesc"
HeaderText="Que stion"
ItemStyle-HorizontalAlign ="Left"></
asp:BoundField>
<asp:TemplateFi eld HeaderText="Ans wer">
<ItemTemplate >
<asp:RadioButto nList
RepeatDirection ="Horizontal " runat="server"
ID="rdAnswer" SelectedIndex=' <%#
SetState(DataBi nder.Eval
(Container.Data Item,"Answer")) %>'>
<asp:ListItem Value="0">Yes</
asp:ListItem>
<asp:ListItem Value="1">No</
asp:ListItem>
</asp:RadioButton List>
</ItemTemplate>
</asp:TemplateFie ld>
</Columns>
</asp:GridView>

Hello,

I need to create a gridview programmaticall y in code that would be
similar to the above code (in design mode).\

Any pointers?

Thanks,

Mar 28 '07 #2
Hello John,

Following are some of the issues in the example you cited:
(1) All columns of datatable will be displayed. In my case, I need
some columns to be visible and some are not.
(2) Does not handle DataKeys that I need
(3) Does not handle adding a control like the radiobuttonlist that I
need

In a post from the same thread - "why not a basic gridview? .....
since one your example you are not doing additional formatting to the
data other than creating bound columns."

Thanks for you assistance.
On Mar 28, 4:09 pm, "John Timney \(MVP\)"
<x_j...@timney. eclipse.co.ukwr ote:
Someones already done it for you.http://forums.asp.net/thread/1379019.aspx

Not sure why you wouldn't just use a templated gridview though!

Regards

John Timney (MVP)http://www.johntimney.comhttp://www.johntimney.com/blog
Mar 28 '07 #3
I didn't think the example gave you a perfect solution, only that it would
give you an idea of how to create a datagrid dynamically.

If you use a template against a gridview then you can BIND and EVAL against
any of the datatable values and structure your output as you need it,

Regards

John Timney (MVP)
http://www.johntimney.com
http://www.johntimney.com/blog
"NKaufman" <na****@hotmail .comwrote in message
news:11******** **************@ y80g2000hsf.goo glegroups.com.. .
Hello John,

Following are some of the issues in the example you cited:
(1) All columns of datatable will be displayed. In my case, I need
some columns to be visible and some are not.
(2) Does not handle DataKeys that I need
(3) Does not handle adding a control like the radiobuttonlist that I
need

In a post from the same thread - "why not a basic gridview? .....
since one your example you are not doing additional formatting to the
data other than creating bound columns."

Thanks for you assistance.
On Mar 28, 4:09 pm, "John Timney \(MVP\)"
<x_j...@timney. eclipse.co.ukwr ote:
>Someones already done it for
you.http://forums.asp.net/thread/1379019.aspx

Not sure why you wouldn't just use a templated gridview though!

Regards

John Timney (MVP)http://www.johntimney.comhttp://www.johntimney.com/blog

Mar 28 '07 #4

Hi,

To generate a gridView programmaticall y, you need to create a GridView
object and assign the properties that you had mentioned.
BoundField objects can be created and added to the gridview object.
Problem comes only when you need to add an ItemTemplate column. I tried a
sample code for the exact same gridView code that you had posted.

//My sample datatable which i am using to bind to the grid view.
DataTable dtSource = new DataTable();
dtSource.Column s.Add("Question ID");
dtSource.Column s.Add("Question Desc");
dtSource.Column s.Add("Answer") ;
dtSource.Column s.Add("isHeadin g");

DataRow dr = dtSource.NewRow ();
dr[0] = "Q1";
dr[1] = "I like reading books ";
dr[2] = "1";
dr[3] = "true";
dtSource.Rows.A dd(dr);

dr = dtSource.NewRow ();
dr[0] = "Q2";
dr[1] = "I watch a lot of TV";
dr[2] = "0";
dr[3] = "false";
dtSource.Rows.A dd(dr);
//Creating a gridView

GridView gvBasic = new GridView();

gvBasic.DataKey Names="Question ID,isHeading".S plit(",".ToChar Array());
gvBasic.AutoGen erateColumns = false;
gvBasic.AllowPa ging = true;
gvBasic.PageSiz e = 100;
gvBasic.DataSou rce = dtSource;

//Your column 1 that is hidden

BoundField objCol1 = new BoundField();
objCol1.Visible = false;
objCol1.DataFie ld = "QuestionID ";
objCol1.HeaderT ext = "QuestionID ";
gvBasic.Columns .Add(objCol1);

//Your column 2 that has the questions

BoundField objCol2 = new BoundField();
objCol2.DataFie ld = "QuestionDe sc";
objCol2.HeaderT ext = "Question";
objCol2.ItemSty le.HorizontalAl ign = HorizontalAlign .Left;
gvBasic.Columns .Add(objCol2);

//ItemTemplate is an Interface in dotnet and hence,
//Create an ItemTemplate class which implements the interface.

// Your column three which has the radiobuttonList on it

TemplateField objCol3 = new TemplateField() ;
objCol3.HeaderT ext = "Answer";
ItemTemplate objTemplate = new ItemTemplate("r dAnswer", dtSource);
objCol3.ItemTem plate = objTemplate;

gvBasic.Columns .Add(objCol3);

gvBasic.DataBin d();
Page.Form.Contr ols.Add(gvBasic );

Code for the ItemTemplate class:
public class ItemTemplate : ITemplate
{

string ControlName = "";
object DataSource = null;

//ControlName: Name of the radio button list.
// DataSource is the datatable to which the gridview is bound to.

public ItemTemplate(st ring ControlName,obj ect DataSource)
{
this.ControlNam e = ControlName;
this.DataSource = DataSource;
}
public void InstantiateIn(C ontrol objContainer)
{
RadioButtonList rdAnswer = new RadioButtonList ();
rdAnswer.ID = this.ControlNam e;

//An event is added to traverse every row that is bound to the
//gridview to fetch the answer column.

rdAnswer.DataBi nding += new EventHandler(th is.OnDataBindin g);
ListItem lst1 = new ListItem("Yes", "0");
ListItem lst2 = new ListItem("No"," 1");
rdAnswer.Items. Add(lst1);
rdAnswer.Items. Add(lst2);
objContainer.Co ntrols.Add(rdAn swer);

}

public void OnDataBinding(o bject sender, EventArgs e)
{
RadioButtonList rdAnswer = (RadioButtonLis t)sender;
GridViewRow container = (GridViewRow)rd Answer.NamingCo ntainer;

//Setting the value of the selected index - This is the replacement for the
eval.

rdAnswer.Select edIndex =
int.Parse(((Dat aRowView)contai ner.DataItem).R ow.ItemArray[2].ToString());

}

}

I guess you shd be all set with this code sample above.

- Parvathy Padmanabhan
Mar 30 '07 #5
Parvathy,

Excellent. I will try this and let you know.
Thanks,

On Mar 30, 6:46 pm, Parvathy Padmanabhan
<ParvathyPadman ab...@discussio ns.microsoft.co mwrote:
Hi,

To generate a gridView programmaticall y, you need to create a GridView
object and assign the properties that you had mentioned.
BoundField objects can be created and added to the gridview object.
Problem comes only when you need to add an ItemTemplate column. I tried a
sample code for the exact same gridView code that you had posted.

//My sample datatable which i am using to bind to the grid view.
DataTable dtSource = new DataTable();
dtSource.Column s.Add("Question ID");
dtSource.Column s.Add("Question Desc");
dtSource.Column s.Add("Answer") ;
dtSource.Column s.Add("isHeadin g");

DataRow dr = dtSource.NewRow ();
dr[0] = "Q1";
dr[1] = "I like reading books ";
dr[2] = "1";
dr[3] = "true";
dtSource.Rows.A dd(dr);

dr = dtSource.NewRow ();
dr[0] = "Q2";
dr[1] = "I watch a lot of TV";
dr[2] = "0";
dr[3] = "false";
dtSource.Rows.A dd(dr);

//Creating a gridView

GridView gvBasic = new GridView();

gvBasic.DataKey Names="Question ID,isHeading".S plit(",".ToChar Array());
gvBasic.AutoGen erateColumns = false;
gvBasic.AllowPa ging = true;
gvBasic.PageSiz e = 100;
gvBasic.DataSou rce = dtSource;

//Your column 1 that is hidden

BoundField objCol1 = new BoundField();
objCol1.Visible = false;
objCol1.DataFie ld = "QuestionID ";
objCol1.HeaderT ext = "QuestionID ";
gvBasic.Columns .Add(objCol1);

//Your column 2 that has the questions

BoundField objCol2 = new BoundField();
objCol2.DataFie ld = "QuestionDe sc";
objCol2.HeaderT ext = "Question";
objCol2.ItemSty le.HorizontalAl ign = HorizontalAlign .Left;
gvBasic.Columns .Add(objCol2);

//ItemTemplate is an Interface in dotnet and hence,
//Create an ItemTemplate class which implements the interface.

// Your column three which has the radiobuttonList on it

TemplateField objCol3 = new TemplateField() ;
objCol3.HeaderT ext = "Answer";
ItemTemplate objTemplate = new ItemTemplate("r dAnswer", dtSource);
objCol3.ItemTem plate = objTemplate;

gvBasic.Columns .Add(objCol3);

gvBasic.DataBin d();
Page.Form.Contr ols.Add(gvBasic );

Code for the ItemTemplate class:

public class ItemTemplate : ITemplate
{

string ControlName = "";
object DataSource = null;

//ControlName: Name of the radio button list.
// DataSource is the datatable to which the gridview is bound to.

public ItemTemplate(st ring ControlName,obj ect DataSource)
{
this.ControlNam e = ControlName;
this.DataSource = DataSource;
}

public void InstantiateIn(C ontrol objContainer)
{
RadioButtonList rdAnswer = new RadioButtonList ();
rdAnswer.ID = this.ControlNam e;

//An event is added to traverse every row that is bound to the
//gridview to fetch the answer column.

rdAnswer.DataBi nding += new EventHandler(th is.OnDataBindin g);
ListItem lst1 = new ListItem("Yes", "0");
ListItem lst2 = new ListItem("No"," 1");
rdAnswer.Items. Add(lst1);
rdAnswer.Items. Add(lst2);
objContainer.Co ntrols.Add(rdAn swer);

}

public void OnDataBinding(o bject sender, EventArgs e)
{
RadioButtonList rdAnswer = (RadioButtonLis t)sender;
GridViewRow container = (GridViewRow)rd Answer.NamingCo ntainer;

//Setting the value of the selected index - This is the replacement for the
eval.

rdAnswer.Select edIndex =
int.Parse(((Dat aRowView)contai ner.DataItem).R ow.ItemArray[2].ToString());

}

}

I guess you shd be all set with this code sample above.

- Parvathy Padmanabhan

Apr 3 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2222
by: | last post by:
I'm wondering if it's possible, outside of the declaration of an ASP.NET 2.0 GridView, to programmatically style individual columns. For example, I might want to make the text in a particular column bold, or larger. I know that Templates and other declarative mechanisms exist to make this happen. I'm wondering if you can apply the styling using code only. What is the general syntax? Flash Actionscript has this "after the fact"...
5
15332
by: Brian McClellan | last post by:
Just wondering if anyone has a simple example of creating a gridview completely programmatically, i'm not doing anything terribly sophisticated. When creating the gridview declaratively evertying works fine, however programmatically, while the grid will display data that exsists in the database, any operation on the data ( editing/updating/deleting ) seems to cause a rowdeleting/updating etc error. Or is this simply not meant to be done?
0
1302
by: Chris | last post by:
Hi, Can I add a new row to gridview programmatically, similar to ADD method of listbox ? Thanks a lot in advance.
1
1878
by: pApAk | last post by:
Hi, i am working at .NET Web-Application (c# codebehind) and i have placed on my web-site a GridView, aka DataGrid (that works as Server control). This GridView generated following code in HTML-source: <asp:GridView ID="GridView1" runat="server"> </asp:GridView> Is there a way to "reach" a GridView (or a GridView-Row) via Javascript? For
2
8764
by: Philip | last post by:
I can use a GridView and ObjectDataSource to bind my data using "Eval" expressions ... provided the GridView and related Column TemplateFields are defined as inline HTML. I prefer to programmatically create the GridView Column/ TemplateField definitions at runtime.... because I do not know the number of applicable columns until runtime. The addition of the GridView Column/ TemplateFields work fine, however the "Eval" expressions do not...
0
2258
by: cook.jonathan.m | last post by:
I want to programmatically add a dropdown to each row in a certain column returned to the gridview by my query. I want to do this entirely in behind-code. My gridview tag in the page will have the following code and no more. <asp:GridView ID="gv" runat="server" AutoGenerateColumns="false"> </asp:GridView> Now, I have generated boundfields to add regular data without a
4
12580
by: Tomasz | last post by:
Hello Developers, Here is interesting problem I just came across: how do I wire a GridView control programmatically? Here is my sample code using Object Data Source: protected void Page_Load(object sender, EventArgs e) { ObjectDataSource ods = new ObjectDataSource("MyTestTableAdapter",
0
1132
by: Don Miller | last post by:
Without a SQLDataSource declaratively linked to a GridView, I programmatically create a dataset and bind it to a GridView with EnableSortingAndPagingCallbacks=True and Paging=True. The GridView displays (in a View of a MultiView) but when I press the page numbers to page through the dataset, the GridView disappears completely (is not rendered) without a postback. When I take action (press a button) to show the GridView again, the GridView...
3
2763
by: =?Utf-8?B?QW5nZWw=?= | last post by:
I seem to understand how the control works as long as I mated to SqlDataSource or ObjDataSource it works fine. But I do not want to flatten my design in this manner. I am interested in how I can programmatically manipulate the control. In other words maybe just use the data source then extract from the control the information do with it as I see fit. The opposite is also true. I want to be able to add or modify the data in the...
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10211
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10045
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7409
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5299
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3959
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.