Dynamically Templated GridView with Edit, Delete and Insert Options
page 1 of 7
Published: 22 Jan 2007
Abstract
In this article the author presents a comprehensive solution to build a GridView with template fields generated at run time with in-place Insert, Delete and Edit operations with a full description of an effective implementation and usage of ITemplate interface.
by Mahr G. Mohyuddin
Feedback
Average Rating: 
Views (Total / Last 10 Days): 110368/ 4373

Introduction

In many situations we want to bind a fully, in-place operational GridView with a dynamically changing data source. This article shows how GridView can be templated programmatically at run time and how is it possible to do edit, insert and delete operations on it. Although just binding the GridView with some dynamically changing datatsource is a simple and straight job which does not need templated GridView, it cannot facilitate us with the aforementioned operations. To make the GridView simultaneously an operational one, we need to template it dynamically which also requires dynamically generated queries for corresponding operations according to the GridView's data source.

It is useful in many applications especially those that require data manipulation functionality of Enterprise Manager on client side i.e. displaying any table of any database with options for all possible operations on client side. This solution provided in this article will be the best and probably the only way to make it all possible. This article shows how ITemplate is implemented effectively to achieve all of this.

Figure 1


View Entire Article

Article Feedback

Title:  
Name:  
Url: ( Optional )
Comment:  
Please add 6 and 1 and type the answer here:

User Comments

Title: Grid Format   
Name: Castro
Date: 5/8/2008 5:57:47 PM
Comment:
One more question:

How do I set alignment in a cell?(right or left)
I´m really "BALD" trying to do this....

Thank´s in advance
Please, save myself...
Title: Excelent job   
Name: Horacio Grischinsky
Date: 5/7/2008 12:45:47 PM
Comment:
Just I need, now I am chaining this in a 3 layers object aerquitecture, when I finish it ,I promise, to send you a copy.
Title: Re: Grid formatting   
Name: Mahr G. Moyuddin
Date: 4/30/2008 11:24:49 AM
Comment:
I am sorry for late reply. You may do that in following snippet of InstitateIn method. set textbox;'s width 100% that will fit to its container

TextBox field_txtbox = new TextBox();
field_txtbox.width="100%
field_txtbox.ID = FieldName;
ield_txtbox.Text = String.Empty;
Title: Grid formatting   
Name: Nilmar P. Castro
Date: 4/25/2008 4:23:06 PM
Comment:
Is it possible to set a textbox width with the same column width?

How can I do that?

Your help will be greatly appreciated.
Title: Mr   
Name: Nilmar P. Castro
Date: 4/23/2008 5:06:28 PM
Comment:
Excellent Article.
But I´m having problems in change a Header Text, Font, and font-size.
How do I? Can you help me?
Congratulations
Title: Session properties not instantiated   
Name: John
Date: 4/22/2008 12:46:27 PM
Comment:
Your GridView may be the perfect match for a project on which I am working. However, I am having trouble getting it to work. I have entered the server, user name, etc. into the text boxes, but when I click the Connect button, I get the following error in the btnConnect_Click event handler: NullReferenceException was unhandled when it hits the Session["Server"] line.

Here's the code in the event handler:
protected void btnConnect_Click(object sender, EventArgs e)
{
msg_lbl.Text = "";
HttpContext.Current.Session["Server"] = server_tb.Text;
HttpContext.Current.Session["UserName"] = user_tb.Text;
HttpContext.Current.Session["Password"] = pswrd_tb.Text;
etc....
Am I missing a "using" or a Reference or something in Global.asax? Your help will be greatly appreciated.
Title: Thanks   
Name: Muhammad Afnan Khan
Date: 4/21/2008 5:07:37 AM
Comment:
You solved my Problem
Title: VB version   
Name: error_Man46
Date: 4/18/2008 3:23:30 PM
Comment:
VB version = http://code.msdn.microsoft.com/DynamicTemplateClass
Title: Rephrase   
Name: Mike-MD
Date: 4/9/2008 9:05:34 AM
Comment:
Mahr,

I understand. I understand exactly what you mean and do agree that you explained the ITemplate interface. I think you did a great Job nonetheless.

I forgot to add something. For those who need a VB equivalent, the msdn web site has directions to achieving this and it was a great help to me (it actually explains the whole process in VB) heres the link below:

http://msdn2.microsoft.com/en-us/library/0e39s2ck.aspx
Title: Re: Inconsistencies   
Name: Mahr G. Mohyuddin
Date: 4/9/2008 6:22:05 AM
Comment:
Hi,

Mike and Ben, Thanks for your comments. Yes there might be inconisities in convetions I used yet i have explained ITemplate in begining, i.e the pupose of using it. I tried myself to keep it compact. Well there is always room to improve. I will try to more elobarate the things in near futue.
Title: Bottom line, the code works if you can read it.   
Name: Ben-USA
Date: 4/9/2008 2:34:53 AM
Comment:
The bottom line is that the technique was shared. I just actually have a dynamic DataTable that is generated at runtime and his code worked well displaying the data on gridview.
Title: Inconsistencies   
Name: Mike-MD
Date: 4/8/2008 4:06:32 PM
Comment:
Hi,

After reviewing your code, I successfully made a VB equivalent. I'd just like to point out that you have some inconsistencies in your naming conventions..(You interchange the names of your declared variables), which is somewhat frustrating. Further more, your descriptions of your methods and scenarions leading to them are (in my opinion)niether intuitive nor explained properly (i.e the need for creating a Handler for the imagebuttons in your class & also explaining why you are Implementing the Itemplate Interface for those who do not understand the concept of implementation). Your code goes on the general assumption that everyone reading this is an advanced programmer, which (relating to myself) was no the case at first when I saw this article (I was one of the people who shared in the frustration of trying to decipher certain idiomatic conventions that were not explained here).

Overall, I think you did a good job. But I urge you to try to explain certain things further.
Title: You're Awesome   
Name: Ben-USA
Date: 4/7/2008 2:06:56 AM
Comment:
Wow. did I say wow? Well, this article is a wow. Thanks for the technique! Thank you!
Title: Re: Edit,Delete in GridView   
Name: Mahr G. Mohyuddin
Date: 4/2/2008 9:39:28 AM
Comment:
No problem. You may contact me on my personal email address
Title: Edit,Delete in GridView   
Name: Prasad
Date: 3/31/2008 6:47:47 AM
Comment:
I'm a fresher in Soft: Programming , Can u help me
how to make Edit, delete functional in Grid View .
Title: jafar   
Name: jafar
Date: 3/28/2008 10:45:45 AM
Comment:
hello how are you?
Title: Grid starting in edit mode   
Name: Bob
Date: 3/27/2008 4:11:49 PM
Comment:
Hi, anyone else have this problem? I am unable to determine why the grid has started in edit mode (textboxes instead of labels). I want the ItemTemplate to be labels so they're not editable. Please help.
Title: Re: VB Conversion?   
Name: Mahr G. Mohyuddin
Date: 3/22/2008 3:01:09 AM
Comment:
Can u please me the converted solution you have so far. I will make correction and will send to you.
Title: VB Conversion?   
Name: CB
Date: 3/21/2008 2:56:50 PM
Comment:
Hi Mahr - Great Work! Thanks!
Do you have a VB solution yet? I unsuccessfully attempted to convert this to VB. Still 12 errors left. Here are a few...

(1)
insert_button.Click += New ImageClickEventHandler(insert_button_Click)

field_lbl.DataBinding += New EventHandler(OnDataBinding)

(2)
'add templated fields to the GridView
Dim BtnTmpField As TemplateField = New TemplateField()
BtnTmpField.ItemTemplate = New DynamicallyTemplatedGridViewHandler(ListItemType.Item, "...", "Command")

BtnTmpField.HeaderTemplate = New DynamicallyTemplatedGridViewHandler(ListItemType.Header, "...", "Command")

BtnTmpField.EditItemTemplate = New DynamicallyTemplatedGridViewHandler(ListItemType.EditItem, "...", "Command")
TableGridView.Columns.Add(BtnTmpField)
Title: How to make discussion forum in asp.net   
Name: Riya
Date: 3/17/2008 7:05:49 AM
Comment:
Sorry this is not related to ur article but I know u can help me out.I want to create Discussion forum page in my web site.but i dont know how to do,which control should i use, please guide me. Or if u have any link plese give me.
Title: Re: How to include drop down list in one column while editing   
Name: Mahr G. Mohyuddin
Date: 2/27/2008 3:31:20 AM
Comment:
Ok. You have to clear previous rows from table before binding it again. In void PopulateDataTable()
Title: Re: How to include drop down list in one column while editing   
Name: Riya
Date: 2/27/2008 1:28:24 AM
Comment:
Thanks i have completed with drop down list. I have copied ur code as it is but when i click on edit rows gets doubled means in table there r 4 rows,when i click on edit it shows 8 rows with repeated data.
Title: Re: How to include drop down list in one column while editing   
Name: Mahr G. Mohyuddin
Date: 2/25/2008 2:16:29 AM
Comment:
sorry i m unable to post a long reply server is not supproting this. You can add dropdownlist or any other control only in InstaitateIn method. See default is TextBox object you may take Dropdownlist and handle databinding event accrodingly i.e. you have to set DataTextField, DatatValueField, DataSource properties and DataBind() method.

regards.
Mohyuddin
Title: hi   
Name: Nirali
Date: 2/25/2008 12:46:17 AM
Comment:
How to include drop down list in one column while editing
Title: How to include drop down list in one column while editing   
Name: Riya
Date: 2/22/2008 8:13:55 AM
Comment:
Nice article.But How to include drop down list in one column while editing.Please send me this very urgent.
Title: aa   
Name: aa
Date: 2/19/2008 6:23:07 AM
Comment:
Hi David,
Can u please try this.

protected void insert_button_Click(Object sender, EventArgs e)
{
Page page = new Page();
page.Session("InsertFlag")=1;
}

Let me know if u have still problem.
Title: How to write coding for GridView Edit/Update button   
Name: K.Manjunath
Date: 2/8/2008 10:12:12 AM
Comment:
How to implement GridView in Edit/Update button for textbox and the same data should be deleted and enter the new data inserted in GridView.
Title: How to implement delete,Add,edit   
Name: suga
Date: 2/1/2008 12:24:22 AM
Comment:
how to implement delete operation when we use delete button for text box and the same data should be deleted in gridview
Title: How add a filter   
Name: Peter
Date: 1/24/2008 2:32:33 PM
Comment:
Thanks for your nice work! I am a new asp.net programmer.
I am trying to add a DropDownList as a filter to select part or full table from another table.

I add following codes:
string strCode = (string)Session["FieldSelected"];

SqlDataAdapter adapter = new SqlDataAdapter("Select * from " + TableName, Connection);

try
{

if (strCode == "[ALL]")
{
adapter.Fill(Table);
} else
{ DataView dv = new DataView(Table);
dv.RowFilter = Table.Columns[0] + "=" + strCode;
TableGridView.DataSource = dv;
TableGridView.DataBind();
}

However, it did not work. Would you please give me some hints. Thanks!
Title: Re: Nice Article & Sorting   
Name: Mahr G. Mohyuddin
Date: 1/22/2008 12:27:34 AM
Comment:
Thanks Hari!
for your comments.

Diana!
I will take care of this as soon as i find time. I will publish it after incorporating your suggestion.
Thanks.
Title: Nice Article, Very Impressive Presentation   
Name: Hari Krishnan
Date: 1/22/2008 12:21:03 AM
Comment:
Thanks Bhaaaiiiii.
Title: How to implement the sorting   
Name: Diana
Date: 1/21/2008 4:29:06 PM
Comment:
The GridView control raises the Sorting event when a Sort button (a button with its CommandName property set to "Sort") is clicked, but before the GridView control handles the sort operation. This allows you to provide an event-handling method that performs a custom routine, such as canceling the sorting operation, whenever this event occurs.

So change the header by LinButton and then implement the GridView sorting method.
Title: how to implement delete operation when we use delete button for text box and the same data should be deleted in gridview   
Name: meghna
Date: 1/21/2008 12:11:06 AM
Comment:
its very urgent
Title: sehr   
Name: Derstier
Date: 1/20/2008 4:13:58 PM
Comment:
sehr gut arbeite!!! viele danke
Title: Datagrid   
Name: satheesh
Date: 1/19/2008 5:33:42 AM
Comment:
good share
Title: How to implement the Sorting, Please help...   
Name: Frank
Date: 1/17/2008 3:52:09 PM
Comment:
I figure out by myself. In short, the literal does not make the HeaderText clickable, so it needs to use linkbutton instead inside the handler class.

In addition, inside the class, it also need to add a event handler for linkbutton click from where you can call gridview sorting function directly.
Title: How to implement the Sorting, Please help...   
Name: Frank
Date: 1/17/2008 1:35:43 PM
Comment:
Thank you for your great article. I'm trying to make the header clickable in order to do sorting on each column, but failed.

Generally speaking, where is the place to add 'SortExpression = ColumnName'? I know it's not enough to just set AllowSorting="True" inside the gridview control. Thank you!
Title: Re:Multiple User   
Name: Mahr G. Mohuddin
Date: 1/17/2008 12:05:30 AM
Comment:
Hi,
You need to implement optimistic concurrency in your application to get rid of this problem in multi user environment. For this you need to keep a version field in the table being bound to the grid. It should be 0 by default (when record is inserted). Increment it while updating/deleting it. When you load in edit mode keep the version in viewstate or session or in some hidden field. Whenever it is refreshed or re-loaded match its new version with the one saved in session. if there is a mismatch you need to simply alert the user to show messages like "re-acces the record!" or if not found (deleted)show "record no longer exists!".
Title: Multiple User   
Name: Harsh
Date: 1/16/2008 1:35:42 PM
Comment:
Hi,

This article was very helpful.
However, it would not work in multi-user environment.

Say for instance, User A and B load the same page. User B deletes row # 5 while User A is still viewing the old data. Then User A clicks row # 7 for editing. When data refreshes on postback, User A sees that the row in edit state is not the one he/she selected (The orignal row #7 has now become row #6 as User B deleted a row and User A was looking at out-of-date data).

Can you suggest a workaround for this scenario?

Thanks.
Title: How to Implemet the Sorting   
Name: Adnan
Date: 12/19/2007 12:56:57 PM
Comment:
Asalm Alikum
I tried AllowSorting property to True and
protected void TableGridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = GridView1.DataSource as DataTable;

if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
but this code didnt work...the column header are not clickable... please advise and help..
Title: Re: disable edit for selected rows   
Name: G. Mohyuddin
Date: 12/14/2007 7:28:30 AM
Comment:
W/slaam
Since button for delete/insert/edit or any other control is added in InstatitateIn method that is called before databinidng.So no decision can be taken to on that time. If you are following my implementation you can try (i m not sure) to call InstatitateIn method once again after databinding and may add check here in following case adding the button for edit, and the key value can be set in some session vaiable.

case "Button":
// add an if statement here for check

ImageButton edit_button = new ImageButton();
edit_button.ID = "edit_button";
edit_button.ImageUrl = "~/images/edit.gif";
edit_button.CommandName = "Edit";
edit_button.ToolTip = "Edit";

edit_button.Click += new ImageClickEventHandler(edit_button_Click);
Container.Controls.Add(edit_button);
Title: disable edit for selected rows   
Name: kashif
Date: 12/14/2007 6:35:07 AM
Comment:
asalam ,, i ve bind my gridview with a dataset, and has allowed auto generate edit to true, now for some of these rows i want to disable this ... how to achieve this,, it would be great if any one in the blob answes me
Title: Re: Button Redirect   
Name: G. Mohyuddin
Date: 10/3/2007 12:36:53 AM
Comment:
Hi,
Whenever a button is created in GridView and u want the fields info of the particular row in which it has been clicked, u must handle RowCommand event of the GridView. a little about it from msdn.

"The RowCommand event is raised when a button is clicked in the GridView control. This allows you to provide an event-handling method that performs a custom routine whenever this event occurs.

Raising an event invokes the event handler through a delegate. For more information, see Raising an Event.

The OnRowCommand method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class."
Title: Button Redirect   
Name: Milton Almeida
Date: 10/1/2007 10:02:22 AM
Comment:
Hello, can you help me?

I read your article about gridview, it's very good and I'm using in my application.
I created one button in gridview to show details in another page.

My problem is that I'm not meeting a way to click in this button, to catch the field key of gridview and to send it to another page.

Thank you,
Milton.
Title: How to Implemet the Sorting   
Name: Yaseen
Date: 9/24/2007 5:21:03 AM
Comment:
It is not working.should i need to implement Header as a link button?
or what else
Title: Re:How to Implemet the Sorting   
Name: G. Mohyuddin
Date: 9/24/2007 4:10:23 AM
Comment:
W/Slaam, Yasin
Plz set AllowSorting property to True. and then handle the onsorting event in this way.

protected void TableGridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = GridView1.DataSource as DataTable;

if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

GridView1.DataSource = dataView;
GridView1.DataBind();
}
}

i hope it will work.
Title: How to Implemet the Sorting   
Name: Yaseen
Date: 9/24/2007 1:10:15 AM
Comment:
Asalm Alikum
G.Mohyuddin
You have done a great job, but I want to Implement the Sorting what should I do? please help me.
Thanks.
Title: Re: Templated column   
Name: madval
Date: 9/5/2007 3:36:22 PM
Comment:
My mistake, reading my own post I see I was creating a new instance of the CheckBox control (checkbox = new CheckBox()) instead of checkbox = (CheckBox)sender
Title: Templated column   
Name: madval
Date: 9/5/2007 3:33:04 PM
Comment:
First of all, thank you for your work, it's very nice. I'm trying to create a CheckBox templated column for a bit database field, I've read your post about it and I followed the steps you provided. The problem is that when the OnDataBinding event is fired and the CheckBox control is created it doesn't save its Checked and Text properties:

private void OnDataBinding(object sender, EventArgs e)
{
......
case "CheckBox":
CheckBox checkbox = new CheckBox();
checkbox.Checked = Convert.ToBoolean(bound_value_obj);
checkbox.Text = bound_value_obj.ToString();
checkbox.Checked = true; //just testing
break;
......
}

what do you think it's happening?
Title: Templated column   
Name: madval
Date: 9/5/2007 3:32:40 PM
Comment:
First of all, thank you for your work, it's very nice. I'm trying to create a CheckBox templated column for a bit database field, I've read your post about it and I followed the steps you provided. The problem is that when the OnDataBinding event is fired and the CheckBox control is created it doesn't save its Checked and Text properties:

private void OnDataBinding(object sender, EventArgs e)
{
......
case "CheckBox":
CheckBox checkbox = new CheckBox();
checkbox.Checked = Convert.ToBoolean(bound_value_obj);
checkbox.Text = bound_value_obj.ToString();
checkbox.Checked = true; //just testing
break;
......
}
Title: very nice work   
Name: pallawee
Date: 9/3/2007 4:45:56 AM
Comment:
very nice.i have learn a lot of thing about grid through ur article.
Title: Gridview Events not firing.   
Name: GeneB
Date: 8/29/2007 5:52:51 PM
Comment:
Hi G.Mohyuddin

I have yet another question. None of gridview events are firing. I have all the "OnRow..." events setup in source code. I have the InstantiateIn method setup, though I changed the button from Image to Link. I can get the proper fields and data to show in the gridview, but when I click edit, it acts as if there is no data, though it keeps the caption. Anything you could tell me would be great.....

Thanks again,

Gene
Title: Re: Session Object problem   
Name: G. Mohyuddin
Date: 8/15/2007 1:24:35 AM
Comment:
Please try this. and make sure you have added System.Web.UI namespace.

protected void insert_button_Click(Object sender, EventArgs e)
{
Page page = New Page();
page.Session("InsertFlag")=1;
}
Title: Session Object problem   
Name: GeneB
Date: 8/13/2007 2:32:32 PM
Comment:
Hi Mr. Mohyuddin,

Nice bit of code here. I have successfully translated it from C# to VB, but I am having a problem with the Session. I cannot refer to the session from my code in the App_Code folder. Any way around this?

Gene
Title: Re: Needs the Checkboxex when the database field is Bit   
Name: G. Mohyuddin
Date: 8/9/2007 10:07:52 AM
Comment:
Hi Suresh,
It is easy to add. just you have to see how TextBox and Label is being added in InstatiateIn method. Add a new condition for if InfoType="CheckBox" then make new instance of check box and add it like

Container.Controls.Add(checkbox);
Also regiter its binding handlers like we have set for textBox and lable and bind it in its definition.

Add it for both ItemTemplate and EditItemTemplate (for first set its enabled false)

Add these rows to add new column for it in constructor of the class in CreatTmpltdGrivView method as it has been called other coulmns. like

TemplateField CheckBoxTmpField = new TemplateField();
BtnTmpField.ItemTemplate =
new DynamicallyTemplatedGridViewHandler(ListItemType.Item, "...", "CheckBox");
BtnTmpField.HeaderTemplate =
new DynamicallyTemplatedGridViewHandler(ListItemType.Header, "...",
"CheckBox");
BtnTmpField.EditItemTemplate =
new DynamicallyTemplatedGridViewHandler(ListItemType.EditItem, "...",
"CheckBox");
TableGridView.Columns.Add(CheckBoxTmpField);
Title: Needs the Checkboxex when the database field is Bit   
Name: Suresh
Date: 8/9/2007 8:40:53 AM
Comment:
Hi Mohyuddin,
Your Example Code is nice and helpful to the Developers. I need to display the checkboxes for a columnname(Status) and values (Active=1, InActive=0). Could you help me to overcome the problem.. It would be a greathelp for me...
Title: Verynice   
Name: Mervin
Date: 8/8/2007 3:44:55 AM
Comment:
nice helpful for me thanks
Title: Re: Foriegn Key fields   
Name: G. Mohyuddin
Date: 7/25/2007 1:14:32 AM
Comment:
It is possible to achieve that you need. What you have to do is add a 'case.'for "GrdiView" under second level switch statement in InstantiateIn method. When it will be claled implitely by the GridViewHandler contructor will add a GridView in ItemTemplate of the column instead of button , textbox or label etc.

public void InstantiateIn(System.Web.UI.Control Container)
{
switch (ItemType)
{
case ListItemType.Item:
switch (InfoType)
{
case "GridView":
GridView childGridView = new GridView();
childGridView.DataBinding += new EventHandler (OnDataBinding);
Container.Controls.Add(childGridView);
.....

then add the binding info in DataBinding event handler by introducing one swtich under ItemTemplate i.e.

private void OnDataBinding(object sender, EventArgs e)
{
...
...
switch (ItemType)
{
case ListItemType.Item:
switch (InfoType)
{
Case "GridView" :
GridView childGirdView = (GridView)sender;
// now bind the gridView with appropriate datasource
.....

}
...

In CreateGridView method add TemplateField (as already one has been added for Buttons) set its item,edititem and headertemplate through the gridviewhandler class contructor.

I hope it will work.
Title: Foriegn Key fields   
Name: Neal
Date: 7/24/2007 10:57:16 AM
Comment:
How could you set up something so that cells that are foriegn keys would give you a gridview of the table that it is referencing(which you could then select an item to populate that cell)?

By the way I really think you have a great job here, it is really quite an elegant solution.
Title: Foriegn Key fields   
Name: Neal
Date: 7/23/2007 4:40:38 PM
Comment:
How could you set up something so that cells that are foriegn keys would give you a gridview of the table that it is referencing(which you could then select an item to populate that cell)?

By the way I really think you have done a great job here, it is really quite an elegant solution.
Title: Feed back   
Name: Abbas
Date: 7/23/2007 9:20:27 AM
Comment:
That is some better for understadning the Operations of gridview control.
Title: Re: Brilliant   
Name: G. Mohyuddin
Date: 7/12/2007 12:59:30 AM
Comment:
Thanks, Fareeth.
Alhamdulillah...All praises to Allah.
Title: Brilliant   
Name: Fareeth
Date: 7/11/2007 11:24:57 AM
Comment:
Jazakallah!!!

May allah will reward you for your work!!
Keep it up!!
Title: Re: briliant point pointed out   
Name: G. Mohyuddin
Date: 7/5/2007 8:31:32 AM
Comment:
Thanks Jon!
I have tried my level best to let the developers know how to take maximum benefit from ITemplate interface.
Title: briliant point pointed out   
Name: jon
Date: 7/5/2007 4:04:53 AM
Comment:
This line sure helps..

"It is important to know that the CommandName of insert_button is set to "Edit" just to take advantage of the Edit mode that provides text boxes for all editable items."

Great article, thanks.
Title: Re: $ in the column name casuses problem   
Name: G. Mohyuddin
Date: 7/2/2007 3:07:35 AM
Comment:
Actualy the Eval method of DataBinder class calls GetValueProperty method which takes conatiner and the property name to return the value against it. Unfortuantely Eval method internally trims the name of property upto characters such as dot, dollar, hash, point etc. and passes to GetValueProperty that mismatches what is already in 'System.Data.DataRowView'.

Now the solution is we would call the GetValueProperty method direclty.

It is simple do the following.

In DynamicallyTemplatedGridViewHandler class the handler of OnDatabinding we have
bound_value_obj = DataBinder.Eval(data_item_container.DataItem, FieldName);

chaange it with

bound_value_obj = DataBinder.GetPropertyValue(data_item_container.DataItem, FieldName);

It works fine.
Title: $ in the column name casuses problem   
Name: Kiran
Date: 6/30/2007 12:50:39 PM
Comment:
I am developing a matrix which contains questions as columns. These questions may contain any characters. Currently i am facing problem when my column name contains "$". It works fine when there are no $ signs.
"row.findcontrol" doesnot return anything as the "$" is trimmed from the ID which is given to the dropdown in the edititem. Which is why it is not able to find anything.

Can you tell me a workaround for this? Moreover are there any other characters which may cause problem
Title: Re: disable the edit/delete button   
Name: G. Mohyuddin
Date: 6/29/2007 7:50:17 AM
Comment:
In InstaitiateIn method simply remove the code where button is being added. like it should not be there..

ImageButton edit_button = new ImageButton();
edit_button.ID = "edit_button";
edit_button.ImageUrl = "~/images/edit.gif";
edit_button.CommandName = "Edit";
edit_button.Click += new ImageClickEventHandler(edit_button_Click);
edit_button.ToolTip = "Edit";
Container.Controls.Add(edit_button);

similarly remove code for delete button too.
Title: disable the edit/delete button   
Name: Raj
Date: 6/29/2007 2:46:54 AM
Comment:
Hi,
in .net datagrid i want to disable the edit/delete button.. the date row values wil be enable.
if i yse this "Gridname.Enabled = false;" means all the datas og datagrid is disabled. but i want to disable the edit delete button only.
how can i do that.
Title: re: a question   
Name: Daivd
Date: 6/28/2007 8:48:16 AM
Comment:
hi,G. Mohyuddin
thank you for ur reply, there is no problem on the code at all..

Really appreciate.

David
Title: Dyamic Template with GridView   
Name: Alpesh Dhanesha
Date: 6/22/2007 7:42:59 AM
Comment:
Hi,

Thanks, but this not what i need. i need hierarchy of inner gridview. in which i have to create dynamic template columns. no need to edit template, just item template is required.

Waiting for reply
Thanks a lot
Title: Re: i want to add gridview instead of label   
Name: G. Mohyuddin
Date: 6/22/2007 7:22:33 AM
Comment:
You can use my other solution available at http://www.codeproject.com/aspnet/MultiNestMDGridview.asp
You may add the child GridView in ItemTemplate instead of EditItemTemplate. And you can easily get Edting, Inertion simultenously.
Title: i want to add gridview instead of label   
Name: Alpesh Dhanesha
Date: 6/22/2007 6:45:09 AM
Comment:
Hi,
I want to add a N number of GridView in ItemTmplate like hierarchy of gridview. your code is very very helpful to me to develop it but i need more help.

Hope you help me on this topic
Thanks
Title: Re: a question   
Name: G. Mohyuddin
Date: 6/19/2007 1:13:38 AM
Comment:
Hi David,
Can u please try this.

protected void insert_button_Click(Object sender, EventArgs e)
{
Page page = new Page();
page.Session("InsertFlag")=1;
}

Let me know if u have still problem.
Title: a question   
Name: David
Date: 6/18/2007 3:33:39 PM
Comment:
Hi, G. Mohyuddin,
Thanks a lot for ur code, it really helps a lot.

Now, I am trying to convert ur code into VB version, but I got confused by some parts:

for example:
in C#
protected void insert_button_Click(Object sender, EventArgs e)
{
new Page().Session["InsertFlag"] = 1;
}

after I transfer it to VB, I got:
Protected Sub insert_button_Click(ByVal sender As Object, ByVal e As EventArgs)
New Page().Session("InsertFlag") = 1
End Sub

But I got error message in the visual studio, it said "syntax error"

New Page().Session("InsertFlag") = 1
It seems this line is not correct.

I don't know what's wrong, since I am not familiar with C#, if u can tell me how to transfer this part, I really appreciate.. Thanks.
Title: Re: Validate Fields   
Name: G. Mohyuddin
Date: 6/14/2007 10:07:47 AM
Comment:
Sure you can do it in code. you have to add the validator in InstantiateIn method for the text box. But make sure your all fields require it or add a condition based on the id of the field. then add it
for example the in the last part of InstantiateIn where A TextBox is being instaitated add validators like this.

TextBox field_txtbox = new TextBox();

field_txtbox.ID = FieldName;

RequiredFieldValidator rfv = new RequiredFieldValidator();
rfv.ControlToValidate = field_txtbox.ID;
rfv.ErrorMessage = "This field cant be empty!";
rfv.Text = "!";

// dont forget to add both text box and the validator in the container as follows

Container.Controls.Add(field_txtbox);
Container.Controls.Add(rfv);

Hope it works.
Title: Re: Empty Table Proble   
Name: G. Mohyuddin
Date: 6/14/2007 9:42:38 AM
Comment:
Hi Rajesh! The default behaviour of GridView is that there must be at least one row in table to make table displayable.
You have noticed that Insert option like Edit and Delete is in each row. Hence if there is no row there will be no Insert/Delete/Edit option. And even if i provide Insert button globally, there must have been at least one empty row to be filled i.e. is not supported by GridView.
There are workarounds for it but they deviate from the core intention of the solution.
You may add a fake row in table and do all insertion from GridView and later delete that row. -:)
Title: Validate Fields   
Name: AR
Date: 6/14/2007 8:02:42 AM
Comment:
Is this possible to validate text box fields while inserting or updating (for example date field)
Title: Empty Table Proble   
Name: Rajesh
Date: 6/14/2007 4:47:51 AM
Comment:
Hi Mohyuddin! i read the article it was great.
i have one issue in this. When am opening a table which doesnt have any values. i cannot see any structure of insert,delete and update. it'll be nice that we can add data even if the table is empty. do u have any idea on this? pleas reply
Title: Re: multiple Select   
Name: G. Mohyuddin
Date: 6/4/2007 5:41:26 AM
Comment:
Although updating multiple rows depends upon the WHERE clause in GenerateUpdateQuery method but the GridView control enters into edit mode only for single row. So it is impossible to open multiple multiple rows for editing.
Title: multiple Select   
Name: biren mohanty
Date: 6/2/2007 12:50:50 AM
Comment:
thanks for this codeing for grid view updateing. but one problem that can we edit at a time multiple row.that means
suppose I want to edit multiple rows without updateing after that when I click update button then all rows will be update.if u know then pls send me.
Title: Re: OnDataBinding error   
Name: G. Mohyuddin
Date: 5/25/2007 1:27:58 AM
Comment:
Actualy the Eval method of DataBinder class class GetValueProperty method which takes conatiner and the property name to return the value against it. Unfortuantely Eval method internally trims the name of property upto ponit(.) and passed to GetValueProperty that mismatches what is already in 'System.Data.DataRowView'. Now the solution is we would call the GetValueProperty method direclty.
It is simple do the following.
In DynamicallyTemplatedGridViewHandler class the handler of OnDatabinding we have
bound_value_obj = DataBinder.Eval(data_item_container.DataItem, FieldName);

chnage it with

bound_value_obj = DataBinder.GetPropertyValue(data_item_container.DataItem, FieldName);

It works fine.
Title: OnDataBinding error   
Name: mikey
Date: 5/23/2007 9:37:03 PM
Comment:
ive created a datatable which has a column header of ranged numbers like "0.00 - 9,999.00" and "1,000.00 - 4,999.00". when i try to run the code i get the following error message:

DataBinding: 'System.Data.DataRowView' does not contain a property with the name '0'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: DataBinding: 'System.Data.DataRowView' does not contain a property with the name '0'.

Source Error:


Line 663: Control ctrl = (Control)sender;
Line 664: IDataItemContainer data_item_container = (IDataItemContainer)ctrl.NamingContainer;
Line 665: bound_value_obj = DataBinder.Eval(data_item_container.DataItem, FieldName);
Line 666:
Line 667: switch (ItemType)



it seems the ondatabinding event handler is unable to recognize the column name "0.00 - 9,999.00" and "1,000.00 - 4,999.00".

any help will be greatly appreciated. :)
Title: Re: Stack Overflow   
Name: G. Mohyuddin
Date: 5/22/2007 6:16:53 AM
Comment:
Can u please show the code under onRowUpdating Event. So i will be better able to tell you what's happening.
Title: Stack Overflow   
Name: Tinu
Date: 5/22/2007 5:06:17 AM
Comment:
I'm getting Stack Overflow exception while updating records. Please help me through this.
Title: Re-GridView - Updating event is not fire   
Name: G. Mohyuddin
Date: 5/15/2007 12:00:01 PM
Comment:
My apologies for late reply.
Actually in Page_PreInit event if the request is a postaback then the data has not ben yet laoded from view state therefore it update event will not be successful. use Page_Load event , till this event the control properties have been populated from view state and it does work successfullly.
Hope it will work.
Title: GridView - Updating event is not fire   
Name: Rahul
Date: 5/10/2007 1:14:07 AM
Comment:
Hey, Thanks for your nice article. I am facing some problem on grdiview. Please help me in this.

scenerio is :

Gridview Item, Header , EditItem field are populated on runtime. I am using ITemplate for this purpose. Everything is fine.

Problem:
1. When I am going to open a particular record in Edit mode, record is open as expected but Uppdate Event is not firing. I am creating GridView on Pre_Init Event.

2. Sometime I am also getting Viewstate problem.


Please Help me .


Regards,
Rahul
Title: re:MultiLine textbox mode add issue   
Name: Nomd
Date: 5/5/2007 11:45:13 AM
Comment:
I response my own question, It does work. I got it fixed. thanks
Title: MultiLine textbox mode add issue   
Name: Nomd
Date: 5/5/2007 11:30:07 AM
Comment:
Hi Mohyuddin,
I tried to add this line into hander
field_txtbox.TextMode = TextBoxMode.MultiLine;
field_txtbox.Height = 100;
seems like it desn't effect anything in gridview. why?
Title: Re: Exception in getting TextBox   
Name: G. Mohyuddin
Date: 5/5/2007 1:50:42 AM
Comment:
Hi,
Thanks for using the solution.
It shows that the FindControl method is returning null. Either there is no TextBox against the name of Column[5] or there is wrong column name. Check the column name while debugging and ensure that while creating templates this column was instiatated in TexBox.
Title: Exception in getting TextBox   
Name: webcolin
Date: 5/5/2007 1:44:36 AM
Comment:
Hi Mohyuddin

I read your article, that is great, and very benifit for .NEt developer. thanks

I have my case working about 2days, I can't get it fix.. pls advice

when I try to get multi-line of Description
string strDescription = string.Empty;
strDesp = ((TextBox)(row.FindControl(dt.Columns[5].ColumnName))).Text;

I always get error:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

thanks
Title: ITemplate used instead of IBindableTemplate   
Name: G. Mohyuddin
Date: 4/17/2007 1:17:51 AM
Comment:
Wray Smallwood! Although I could not incorporate an IBindableTemplate example in this article as the the title is not primarily meant for that yet I have changed the current solution for ITemplate. ITemplate can provide the required features under the current title. I am thankful to you for suggesting it, I have removed all references of IBindableTemplate and have used ITemplate.
Title: Re: sorting the dynamic gridview   
Name: GArao
Date: 4/7/2007 2:53:22 PM
Comment:
Looks like gridview just won't support sorting a templated column. I changed the CreateTemplatedGridView code to use a BoundField for one of the columns instead of a TemplateField and sort became active for the column.
Title: Re: sorting the dynamic gridview   
Name: GArao
Date: 4/6/2007 3:55:42 PM
Comment:
I created a readonly version of your sample code and here is where I'm adding the sortexpression property. Maybe this is not the right place because the column headings are created as literals instead of linkbuttons. I added the onSorting event handler and allowsorting=true to the gridview declaration.

void CreateTemplatedGridView()
{
// fill the table which is to bound to the GridView
PopulateDataTable();
// add templated fields to the GridView
for (int i = 0; i < Table.Columns.Count; i++)
{
TemplateField ItemTmpField = new TemplateField();
// create HeaderTemplate
ItemTmpField.HeaderTemplate = new GridViewHandler(ListItemType.Header,
Table.Columns[i].ColumnName,
Table.Columns[i].DataType.Name);
// create ItemTemplate
ItemTmpField.ItemTemplate = new GridViewHandler(ListItemType.Item,
Table.Columns[i].ColumnName,
Table.Columns[i].DataType.Name);
ItemTmpField.SortExpression = Table.Columns[i].ColumnName;
// then add to the GridView
TableGridView.Columns.Add(ItemTmpField);

}

// bind and display the data
TableGridView.DataSource = Table;
TableGridView.DataBind();
}

Should the sortexpression be created in the gridview handler instead?
Title: Re: sorting the dynamic gridview   
Name: G. Mohyuddin
Date: 4/6/2007 2:47:05 AM
Comment:
Yes it should support but you need to set SortExpression property of particular field in code and write event handler of OnSorting event of the GridView. this may help you
http://forums.asp.net/thread/1177923.aspx
Title: sorting the dynamic gridview   
Name: GArao
Date: 4/5/2007 6:50:05 PM
Comment:
I tried add sortexpression/allowsorting at the gridview and the item template levels but I can't get the gridview to support sorting. Can it be done?
Title: Re: give me replay of my question   
Name: G. Mohyuddin
Date: 4/3/2007 8:06:30 AM
Comment:
Would you please send me the error description
Title: give me replay of my question   
Name: hitesh panchal
Date: 4/3/2007 7:30:56 AM
Comment:
please replay me on my mail id .

there are in your topic u write this line...
'' string field = ((TextBox)row.FindControl(Table.Columns[i].ColumnName)).Text;''

u convert in vb form and in vb.net i write this in this form
''Dim fields As String = ((TextBox)(row.FindControl(Table.Columns(i).ColumnName)).Text)''

but i have occured error so u help me in form of send me solution on my mail id .

please ........................
Title: Re: update problem   
Name: G. Mohyuddin
Date: 3/5/2007 1:39:04 AM
Comment:
Actually it has been left upto user to decide which column of the table, he decides to be the primary key field. My code assumes it is in first column. I have not disabled it for it will not allow editing in case if the first column is not primary key field. so it's left upto user for deciding the primary key feild and disabling it. Yet you may add samll piece of code to check primark key column dynamically and disable it.
Title: Update Problem   
Name: Francis
Date: 3/1/2007 9:45:19 AM
Comment:
Hi,

It seems that when i try to edit the first column, the update will fail.
Title: Very Nice   
Name: Vikram
Date: 3/1/2007 7:21:15 AM
Comment:
Hi,

Thanks a lot for this article it was a good help to understand how to work with datagrids dynamically through code!
Title: Re GridView   
Name: Graham - South Africa
Date: 2/19/2007 1:44:41 PM
Comment:
Magnificent contribution - solved a lot for me
well done
Title: girdview   
Name: kishore
Date: 2/15/2007 5:29:23 AM
Comment:
how to create dynamic gridview
Title: using ObjectDataSource   
Name: G. Mohyuddin
Date: 2/14/2007 12:43:25 AM
Comment:
Adam,i have not tested it for object data source but i think works fine with object data source as well, you need just to ensure that the InsertFlag has been set properly for using the edit mode for insertion.
Title: Mr   
Name: Adam W
Date: 2/12/2007 8:24:57 AM
Comment:
I found your article from searching for a way of allowing the user to insert into a GridView. I have adapted your code to work with a TableAdapter and ObjectDataSource. The only problem is when clicking Insert it just performs an edit instead. Is there an easier way of inserting new records from within GridView?

Thanks for your time.
Title: Dynamically Templated GridView with Edit, Delete and Insert Options   
Name: Wojtek Szewczyk
Date: 2/11/2007 11:14:37 AM
Comment:
Great example. You saved me a lot of work. I appreciate this.

Wojtek
Title: about VB code   
Name: G. Mohyuddin
Date: 2/7/2007 6:46:08 AM
Comment:
Ok. I am planning to convert the code in near future. Till then you can use any converter like autility at http://www.developerfusion.co.uk/utilities/convertcsharptovb.aspx
Title: ok   
Name: megha
Date: 2/7/2007 6:09:46 AM
Comment:
i want the code in vb.net
i m trainee developer i don't know c#,asp
but i am familier with vb.net
Title: thanks   
Name: chinatn
Date: 2/6/2007 5:48:31 AM
Comment:
thanks
Title: Thanks   
Name: G. Mohyuddin
Date: 2/1/2007 8:44:13 AM
Comment:
Thanks. Fayyaz Bhai. I am very greatful to you for your prayers and best wishes.
Title: Your Work in general   
Name: Fayyaz Khan Lodhi
Date: 2/1/2007 5:16:56 AM
Comment:
AOA GM!

I have gone through the article in a skim. Havent seen the details yet but i just wanted you to know that i am pleased to see your work buddy. May Allah always keep you progressing. Ameen. It's a plausible effort.
Title: Mr   
Name: VP5
Date: 1/31/2007 5:39:06 PM
Comment:
Great programming technique!
Title: Grid View   
Name: Zar and Shafqat
Date: 1/31/2007 7:40:05 AM
Comment:
Congratulation!
This is a big effort of you that you can do this.
May Allah give you more much talent in this field.
SALAM
Title: Thanks   
Name: G. Mohyuddin
Date: 1/26/2007 1:30:28 AM
Comment:
Thanks, Ricky and Amir. I will try to convert the code into ASP.NET/VB.NET 2.0 inshAllah.
Title: (Y)   
Name: M Aamir Mughal
Date: 1/25/2007 11:40:55 PM
Comment:
it is really good work GM ... (Y)

keep it up ... my prays are there :)
Title: Re-About Gridview   
Name: Ricky
Date: 1/25/2007 7:59:49 AM
Comment:
You work is quite appreciatable, kindly do this same in ASP/VB.NET 2.0 for learning purpose. Hope u can Convert this in VB.NET as well
TC
Ricky

Product Spotlight
Product Spotlight 






Ads Powered by Lake Quincy Media
Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2008 ASPAlliance.com  |  Page Processed at 5/12/2008 7:11:55 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search